gancio-upstream/pages/add/_edit.vue
2020-08-16 14:07:44 +02:00

497 lines
18 KiB
Vue

<template lang="pug">
v-container.container
v-card
v-card-title {{edit?$t('common.edit_event'):$t('common.add_event')}}
v-card-text
v-form(v-model='valid')
//- NOT LOGGED EVENT
div(v-if='!$auth.loggedIn')
v-divider <v-icon name='user-secret'/> {{$t('event.anon')}}
p(v-html="$t('event.anon_description')")
//- title
v-text-field.mb-3(v-model='event.title'
:rules="[validators.required('title')]"
:label="$t('event.what_description')"
autofocus
ref='title')
//- description
//- span {{$t('event.description_description')}}
Editor(
v-model='event.description'
:label="$t('event.description_description')"
style='max-height: 400px;')
//- tags
//- div {{$t('event.tag_description')}}
//- client-only
v-combobox.mt-3(v-model='event.tags'
chips small-chips multiple deletable-chips hide-no-data hide-selected
:delimiters="[',', ' ']"
:items="tags.map(t => t.tag)"
:hints="$t('event.tag_description')"
:label="$t('common.tags')")
//- WHERE
//- v-divider
//- i.el-icon-location-outline
//- span {{$t('common.where')}}
//- p(v-html="$t('event.where_description')")
v-combobox(v-model='event.place.name'
:label="$t('common.where')"
:items="places"
item-text='name'
@change='selectPlace')
template(v-slot:item="{ item }")
v-list
v-list-item-content
v-list-item-title {{item.name}}
v-list-item-subtitle {{item.address}}
//- div {{$t("common.address")}}
v-text-field(ref='address' :label="$t('common.address')" v-model='event.place.address' :disabled='disableAddress')
//- WHEN
//- v-divider <v-icon name='clock'/> {{$t('common.when')}}
.text-center
v-btn-toggle(v-model="event.type" color='primary')
v-btn(value='normal' label="normal") {{$t('event.normal')}}
v-btn(value='multidate' label="multidate") {{$t('event.multidate')}}
v-btn(v-if='settings.allow_recurrent_event' value='recurrent' label="recurrent") {{$t('event.recurrent')}}
p {{$t(`event.${event.type}_description`)}}
v-select(v-if='event.type==="recurrent"'
:items="frequencies"
v-model='event.recurrent.frequency')
//- v-option(:label="$t('event.each_week')" value='1w' key='1w')
//- v-option(:label="$t('event.each_2w')" value='2w' key='2w')
//- el-option(:label="$t('event.each_month')" value='1m' key='1m')
client-only
.datePicker
v-date-picker(
:mode='datePickerMode'
:attributes='attributes'
v-model='date'
:locale='$i18n.locale'
:from-page.sync='page'
:is-dark="settings['theme.is_dark']"
is-inline
is-expanded
:min-date='event.type !== "recurrent" && new Date()')
div.text-center.mb-2(v-if='event.type === "recurrent"')
span(v-if='event.recurrent.frequency !== "1m" && event.recurrent.frequency !== "2m"') {{whenPatterns}}
v-radio-group(v-else v-model='event.recurrent.type')
v-radio-button(v-for='whenPattern in whenPatterns' :label='whenPattern.key' :key='whenPatterns.key')
span {{whenPattern.label}}
v-row
v-col
v-menu(v-model='fromDateMenu'
:close-on-content-click="false"
transition="slide-x-transition"
ref='fromDateMenu'
:return-value.sync="time.start"
offset-y
absolute
top
max-width="290px"
min-width="290px")
template(v-slot:activator='{ on }')
v-text-field(
:label="$t('event.from')"
:value='time.start'
v-on='on'
clearable
readonly)
v-time-picker(
v-if='fromDateMenu'
:label="$t('event.from')"
format="24hr"
ref='time_start'
:allowed-minutes="[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]"
v-model='time.start'
@click:minute="$refs.fromDateMenu.save(time.start)")
v-col
v-menu(v-model='dueDateMenu'
:close-on-content-click="false"
transition="slide-x-transition"
ref='dueDateMenu'
:return-value.sync="time.end"
offset-y
absolute
top
max-width="290px"
min-width="290px")
template(v-slot:activator='{ on }')
v-text-field(
:label="$t('event.due')"
:value='time.end'
v-on='on'
clearable
readonly)
v-time-picker(
v-if='dueDateMenu'
:label="$t('event.due')"
format="24hr"
:allowed-minutes="[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]"
v-model='time.end'
@click:minute="$refs.dueDateMenu.save(time.end)")
List(v-if='event.type==="normal" && todayEvents.length' :events='todayEvents' :title='$t("event.same_day")')
//- MEDIA / FLYER / POSTER
v-file-input(
:label="$t('common.media')"
:hint="$t('event.media_description')"
prepend-icon="mdi-camera"
v-model='event.image'
persistent-hint
accept='image/*')
v-card-actions
v-spacer
v-btn(@click='done' :loading='loading' :disabled='!valid || loading'
color='primary') {{edit?$t('common.edit'):$t('common.send')}}
</template>
<script>
import { mapActions, mapState } from 'vuex'
import _ from 'lodash'
import moment from 'moment-timezone'
import Editor from '@/components/Editor'
import List from '@/components/List'
import { validators } from '../../plugins/helpers'
export default {
name: 'NewEvent',
components: { List, Editor },
validate ({ store }) {
return (store.state.auth.loggedIn || store.state.settings.allow_anon_event)
},
async asyncData ({ params, $axios, error, store }) {
if (params.edit) {
const data = { time: {}, event: { place: {} } }
data.id = params.edit
data.edit = true
let event
try {
event = await $axios.$get('/event/' + data.id)
} catch (e) {
error({ statusCode: 404, message: 'Event not found!' })
return {}
}
data.event.recurrent = {}
data.event.place.name = event.place.name
data.event.place.address = event.place.address || ''
if (event.multidate) {
data.date = { start: moment.unix(event.start_datetime).toDate(), end: moment.unix(event.end_datetime).toDate() }
data.event.type = 'multidate'
} else if (event.recurrent) {
data.event.type = 'recurrent'
data.event.recurrent = event.recurrent
} else {
data.event.type = 'normal'
data.date = moment.unix(event.start_datetime).toDate()
}
data.time.start = moment.unix(event.start_datetime).format('HH:mm')
data.time.end = moment.unix(event.end_datetime).format('HH:mm')
data.event.title = event.title
data.event.description = event.description
data.event.id = event.id
data.event.tags = event.tags
return data
}
return {}
},
data () {
const month = moment().month() + 1
const year = moment().year()
return {
validators,
valid: false,
dueDateMenu: false,
fromDateMenu: false,
event: {
type: 'normal',
place: { name: '', address: '' },
title: '',
description: '',
tags: [],
image: {},
recurrent: { frequency: '1w', days: [], type: 'weekday' }
},
page: { month, year },
fileList: [],
id: null,
date: null,
time: { start: '20:00', end: null },
edit: false,
loading: false,
mediaUrl: '',
queryTags: '',
disableAddress: true,
frequencies: [
{ value: '1w', text: this.$t('event.each_week') },
{ value: '2w', text: this.$t('event.each_2w') },
{ value: '1m', text: this.$t('event.each_month') }
]
}
},
computed: {
...mapState(['tags', 'places', 'events', 'settings']),
datePickerMode () {
const modeMap = {
multidate: 'range',
normal: 'single',
recurrent: 'multiple'
}
return modeMap[this.event.type]
},
whenPatterns () {
const dates = this.date
if (!dates || !dates.length) { return '' }
const freq = this.event.recurrent.frequency
const weekDays = _(dates).map(date => moment(date).format('dddd')).uniq().value()
if (freq === '1w' || freq === '2w') {
return this.$t(`event.recurrent_${freq}_days`, { days: weekDays.join(', ') })
} else if (freq === '1m' || freq === '2m') {
const days = _(dates).map(date => moment(date).date()).uniq().value()
const n = Math.floor((days[0] - 1) / 7) + 1
return [
{ label: this.$tc(`event.recurrent_${freq}_days`, days.length, { days }), key: 'ordinal' },
{ label: this.$tc(`event.recurrent_${freq}_ordinal`, days.length, { n, days: weekDays.join(', ') }), key: 'weekday' }
]
} else if (freq === '1d') {
return this.$t('event.recurrent_each_day')
}
return ''
},
todayEvents () {
if (this.event.type === 'multidate') {
if (!this.date || !this.date.start) { return }
const date_start = moment(this.date.start)
const date_end = moment(this.date.end)
return this.events.filter(e =>
!e.multidate
? date_start.isSame(moment.unix(e.start_datetime), 'day') ||
(date_start.isBefore(moment.unix(e.start_dateime)) && date_end.isAfter(moment.unix(e.start_datetime)))
: date_start.isSame(moment.unix(e.start_datetime), 'day') || date_start.isSame(moment.unix(e.end_datetime)) ||
(date_start.isAfter(moment.unix(e.start_datetime)) && date_start.isBefore(moment.unix(e.end_datetime))))
} else if (this.event.type === 'recurrent') {
return []
} else {
const date = moment(this.date)
return this.events.filter(e =>
!e.multidate
? !e.recurrent && date.isSame(moment.unix(e.start_datetime), 'day')
: moment.unix(e.start_datetime).isSame(date, 'day') ||
(moment.unix(e.start_datetime).isBefore(date) && moment.unix(e.end_datetime).isAfter(date))
)
}
},
...mapState(['events']),
attributes () {
let attributes = []
// attributes.push({ key: 'today', dates: new Date(), highlight: { color: 'red' } })
attributes = attributes.concat(this.events
.filter(e => !e.multidate && (!e.parentId || this.event.type === 'recurrent'))
.map(e => ({ key: e.id, dot: { color: this.event.type === 'recurrent' ? 'orange' : 'green' }, dates: moment.unix(e.start_datetime).toDate() })))
if (this.event.type === 'recurrent' && this.date && this.date.length) {
attributes.push({
key: 'recurrent',
dot: { color: 'orange' },
dates: {
weeklyInterval: this.event.recurrent.frequency === '1w' ? 1 : 2,
weekdays: _.map(this.date, date => moment(date).day() + 1),
start: new Date(this.date[0])
}
})
}
attributes = attributes.concat(this.events
.filter(e => e.multidate && !e.parentId)
.map(e => ({
key: e.id,
highlight: {},
dates: { start: moment.unix(e.start_datetime).toDate(), end: moment.unix(e.end_datetime).toDate() }
})))
return attributes
},
// filteredTags () {
// const queryTags = this.queryTags.toLowerCase()
// return _(this.tags)
// .filter(t => !this.event.tags.includes(t.tag))
// .filter(t => t.tag.includes(queryTags))
// // .pick('tag')
// .take(5)
// .value()
// },
// couldProceed () {
// return true
// return (this.event.place.name.length > 0 &&
// this.event.place.address.length > 0 &&
// (this.date && this.time.start) &&
// this.event.title.length > 0)
// }
},
// mounted () {
// this.$refs.title.focus()
// },
methods: {
...mapActions(['addEvent', 'updateEvent', 'updateMeta', 'updateEvents']),
// filterPlaces (q, cb) {
// const query = q.toLowerCase()
// const ret = _(this.places)
// .filter(p => p.name.toLowerCase().includes(query))
// .take(5)
// .map(p => ({ value: p.name }))
// .value()
// ret.unshift({ value: q })
// cb(ret)
// },
selectPlace (p) {
console.error('dentro selecte place ', p)
const place = this.places.find(place => place.id === p)
console.error('vediamo se ho trovato il place', place)
if (place && place.address) {
this.event.place.address = place.address
this.disableAddress = true
} else {
this.disableAddress = false
this.event.place.address = ''
}
this.$nextTick(this.$refs.address.focus)
},
// recurrentDays () {
// if (this.event.type !== 'recurrent' || !this.date || !this.date.length) { return }
// const type = this.event.recurrent.type
// if (type === 'ordinal') { return map(this.date, d => moment(d).date()) } else if (type === 'weekday') { return map(this.date, d => moment(d).day() + 1) }
// },
// },
cleanFile () {
this.event.image = {}
},
async done () {
this.loading = true
let start_datetime, end_datetime
const [start_hour, start_minute] = this.time.start.split(':')
if (!this.time.end) {
this.time.end = (Number(start_hour) + 2) + ':' + start_minute
}
const [end_hour, end_minute] = this.time.end.split(':')
const formData = new FormData()
if (this.event.type === 'multidate') {
start_datetime = moment(this.date.start)
.set('hour', start_hour).set('minute', start_minute)
end_datetime = moment(this.date.end)
.set('hour', end_hour).set('minute', end_minute)
} else if (this.event.type === 'normal') {
start_datetime = moment(this.date).set('hour', start_hour).set('minute', start_minute)
end_datetime = moment(this.date).set('hour', end_hour).set('minute', end_minute)
if (end_hour < start_hour) {
end_datetime = end_datetime.add(1, 'day')
}
} else if (this.event.type === 'recurrent') {
start_datetime = moment().set('hour', start_hour).set('minute', start_minute)
end_datetime = moment().set('hour', end_hour).set('minute', end_minute)
const recurrent = {
frequency: this.event.recurrent.frequency,
days: this.event.recurrent.type === 'ordinal' ? _.map(this.date, d => moment(d).date()) : _.map(this.date, d => moment(d).day() + 1),
type: this.event.recurrent.type
}
if (end_hour < start_hour) {
end_datetime = end_datetime.add(1, 'day')
}
formData.append('recurrent', JSON.stringify(recurrent))
}
if (this.event.image) {
console.error(this.event.image)
formData.append('image', this.event.image)
}
formData.append('title', this.event.title)
formData.append('place_name', this.event.place.name)
formData.append('place_address', this.event.place.address)
formData.append('description', this.event.description)
formData.append('multidate', this.event.type === 'multidate')
formData.append('start_datetime', start_datetime.unix())
formData.append('end_datetime', end_datetime.unix())
if (this.edit) {
formData.append('id', this.event.id)
}
if (this.event.tags) { this.event.tags.forEach(tag => formData.append('tags[]', tag.tag || tag)) }
try {
if (this.edit) {
await this.updateEvent(formData)
} else {
await this.addEvent(formData)
}
this.updateMeta()
this.$router.replace('/')
this.loading = false
this.$root.$message({ type: 'success', message: this.$auth.loggedIn ? this.$t('event.added') : this.$t('event.added_anon') })
} catch (e) {
console.error(e.response)
switch (e.request.status) {
case 413:
this.$root.$message({ type: 'error', message: this.$t('event.image_too_big') })
break
default:
this.$root.$message({ type: 'error', message: e.response.data })
}
this.loading = false
}
}
},
head () {
return {
title: `${this.settings.title} - ${this.$t('common.add_event')}`
}
}
}
</script>
<style style='less'>
.datePicker {
max-width: 500px !important;
margin: 0 auto;
}
.container {
max-width: 1400px;
}
/* #edit_page
i {
font-size: 1.3em;
}
#picker {
max-width: 600px;
}
#edit_page .el-form-item {
display: inline-flex;
}
.el-upload,
.el-upload-dragger {
overflow: hidden;
text-align: center;
margin: 0 auto;
max-width: 80%;
font-size: 2em;
} */
</style>