Allow users to create private form templates (#210)

* Allow users to create private form templates

* Improve back-end efficiency

---------

Co-authored-by: Julien Nahum <julien@nahum.net>
This commit is contained in:
formsdev 2023-10-13 15:41:03 +05:30 committed by GitHub
parent f0939f3992
commit 82d7be3235
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 307 additions and 145 deletions

View File

@ -7,6 +7,7 @@ use App\Http\Requests\Templates\FormTemplateRequest;
use App\Http\Resources\FormTemplateResource;
use App\Models\Template;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class TemplateController extends Controller
{
@ -16,12 +17,16 @@ class TemplateController extends Controller
if ($request->offsetExists('limit') && $request->get('limit') > 0) {
$limit = (int) $request->get('limit');
}
return FormTemplateResource::collection(
Template::where('publicly_listed', true)
->orderByDesc('created_at')
->limit($limit)
->get()
);
$templates = Template::where('publicly_listed', true)
->when(Auth::check(), function ($query) {
$query->orWhere('creator_id', Auth::id());
})
->orderByDesc('created_at')
->limit($limit)
->get();
return FormTemplateResource::collection($templates);
}
public function create(FormTemplateRequest $request)
@ -34,7 +39,8 @@ class TemplateController extends Controller
return $this->success([
'message' => 'Template was created.',
'template_id' => $template->id
'template_id' => $template->id,
'data' => new FormTemplateResource($template)
]);
}

View File

@ -77,6 +77,7 @@ class FormTemplateRequest extends FormRequest
}
return new Template([
'creator_id' => $this->user()?->id ?? null,
'publicly_listed' => $this->publicly_listed,
'name' => $this->name,
'slug' => $this->slug,

View File

@ -14,6 +14,7 @@ class Template extends Model
use HasFactory, HasSlug;
protected $fillable = [
'creator_id',
'name',
'slug',
'description',
@ -41,6 +42,15 @@ class Template extends Model
'publicly_listed' => false,
];
protected $appends = [
'share_url',
];
public function getShareUrlAttribute()
{
return url('/form-templates/'.$this->slug);
}
public function setDescriptionAttribute($value)
{
// Strip out unwanted html

View File

@ -4,6 +4,7 @@ namespace App\Models;
use App\Http\Controllers\SubscriptionController;
use App\Models\Forms\Form;
use App\Models\Template;
use App\Notifications\ResetPassword;
use App\Notifications\VerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@ -140,6 +141,11 @@ class User extends Authenticatable implements JWTSubject
return $this->hasMany(Form::class,'creator_id');
}
public function formTemplates()
{
return $this->hasMany(Template::class, 'creator_id');
}
/**
* =================================
* Oauth Related

View File

@ -18,7 +18,7 @@ class TemplatePolicy
*/
public function create(User $user)
{
return $user->admin || $user->template_editor;
return $user !== null;
}
/**
@ -30,7 +30,7 @@ class TemplatePolicy
*/
public function update(User $user, Template $template)
{
return $user->admin || $user->template_editor;
return $user->admin || $user->template_editor || $template->creator_id === $user->id;
}
/**
@ -42,6 +42,6 @@ class TemplatePolicy
*/
public function delete(User $user, Template $template)
{
return $user->admin || $user->template_editor;
return $user->admin || $user->template_editor || $template->creator_id === $user->id;
}
}

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('templates', function (Blueprint $table) {
$table->foreignIdFor(\App\Models\User::class,'creator_id')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('templates', function (Blueprint $table) {
$table->dropColumn('creator_id');
});
}
};

View File

@ -68,6 +68,15 @@
My Forms
</router-link>
<router-link v-if="userOnboarded" :to="{ name: 'my_templates' }"
class="block block px-4 py-2 text-md text-gray-700 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-100 dark:hover:text-white dark:hover:bg-gray-600 flex items-center"
>
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
</svg>
My Templates
</router-link>
<router-link :to="{ name: 'settings.profile' }"
class="block block px-4 py-2 text-md text-gray-700 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-100 dark:hover:text-white dark:hover:bg-gray-600 flex items-center"
>

View File

@ -18,13 +18,13 @@
</template>
<div class="p-4">
<p v-if="!template">
New template will be create from your form <span class="font-semibold">{{ form.title }}</span>.
New template will be create from your form: <span class="font-semibold">{{ form.title }}</span>.
</p>
<form v-if="templateForm" class="mt-6" @submit.prevent="onSubmit" @keydown="templateForm.onKeydown($event)">
<div class="-m-6">
<div class="border-t py-4 px-6">
<toggle-switch-input name="publicly_listed" :form="templateForm" class="mt-4" label="Publicly Listed?" />
<toggle-switch-input v-if="user && (user.admin || user.template_editor)" name="publicly_listed" :form="templateForm" class="mt-4" label="Publicly Listed?" />
<text-input name="name" :form="templateForm" class="mt-4" label="Title" :required="true" />
<text-input name="slug" :form="templateForm" class="mt-4" label="Slug" :required="true" />
<text-area-input name="short_description" :form="templateForm" class="mt-4" label="Short Description"
@ -74,7 +74,7 @@
<script>
import Form from 'vform'
import store from '~/store'
import { mapState } from 'vuex'
import { mapState, mapGetters } from 'vuex'
import axios from 'axios'
import QuestionsEditor from './QuestionsEditor.vue'
@ -93,7 +93,7 @@ export default {
mounted () {
this.templateForm = new Form(this.template ?? {
publicly_listed: true,
publicly_listed: false,
name: '',
slug: '',
short_description: '',
@ -113,6 +113,9 @@ export default {
industries: state => state['open/templates'].industries,
types: state => state['open/templates'].types
}),
...mapGetters({
user: 'auth/user'
}),
typesOptions () {
return Object.values(this.types).map((type) => {
return {
@ -153,6 +156,7 @@ export default {
if (response.data.message) {
this.alertSuccess(response.data.message)
}
this.$store.commit('open/templates/addOrUpdate', response.data.data)
this.$emit('close')
})
},
@ -162,7 +166,7 @@ export default {
if (response.data.message) {
this.alertSuccess(response.data.message)
}
this.$store.dispatch('open/templates/addOrUpdate', response.data.data)
this.$store.commit('open/templates/addOrUpdate', response.data.data)
this.$emit('close')
})
},
@ -173,7 +177,7 @@ export default {
this.alertSuccess(response.data.message)
}
this.$router.push({ name: 'templates' })
this.$store.dispatch('open/templates/remove', response.data.data)
this.$store.commit('open/templates/remove', this.template)
this.$emit('close')
})
}

View File

@ -20,7 +20,7 @@
</svg>
</v-button>
</template>
<router-link v-if="isMainPage" :to="{name:'forms.show_public', params: {slug: form.slug}}" target="_blank"
<router-link v-if="isMainPage && user" :to="{name:'forms.show_public', params: {slug: form.slug}}" target="_blank"
class="block px-4 py-2 text-md text-gray-700 dark:text-white hover:bg-gray-100 hover:text-gray-900 dark:text-gray-100 dark:hover:text-white dark:hover:bg-gray-600 flex items-center"
v-track.view_form_click="{form_id:form.id, form_slug:form.slug}"
>
@ -67,7 +67,7 @@
</svg>
Duplicate form
</a>
<a href="#" v-if="user && user.template_editor"
<a href="#" v-if="!isMainPage" v-track.create_template_click="{form_id:form.id, form_slug:form.slug}"
class="block block px-4 py-2 text-md text-gray-700 dark:text-white hover:bg-gray-100 hover:text-gray-900 dark:text-gray-100 dark:hover:text-white dark:hover:bg-gray-600 flex items-center"
@click.prevent="showFormTemplateModal=true"
>
@ -117,7 +117,7 @@
</div>
</modal>
<form-template-modal :form="form" :show="showFormTemplateModal" @close="showFormTemplateModal=false"/>
<form-template-modal v-if="!isMainPage && user" :form="form" :show="showFormTemplateModal" @close="showFormTemplateModal=false"/>
</div>
</template>

View File

@ -44,7 +44,7 @@ export default {
watch: {
user () {
this.form.email = this.user.email
this.updateUser()
},
show () {
// Wait for modal to open and focus on first field
@ -59,13 +59,16 @@ export default {
},
mounted () {
if (this.user) {
this.form.name = this.user.name
this.form.email = this.user.email
}
this.updateUser()
},
methods: {
updateUser() {
if (this.user) {
this.form.name = this.user.name
this.form.email = this.user.email
}
},
saveDetails () {
if (this.form.busy) return
this.form.put('api/subscription/update-customer-details').then(() => {

View File

@ -0,0 +1,141 @@
<template>
<section class="bg-white py-12">
<div class="px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 sm:gap-6 relative z-20">
<div class="flex items-center gap-4">
<div class="flex-1 sm:flex-none">
<select-input v-model="selectedType" name="type"
:options="typesOptions" class="w-full sm:w-auto md:w-56"
/>
</div>
<div class="flex-1 sm:flex-none">
<select-input v-model="selectedIndustry" name="industry"
:options="industriesOptions" class="w-full sm:w-auto md:w-56"
/>
</div>
</div>
<div class="flex-1 w-full md:max-w-xs">
<text-input name="search" :form="searchTemplate" placeholder="Search..." />
</div>
</div>
<div v-if="templatesLoading" class="text-center mt-4">
<loader class="h-6 w-6 text-nt-blue mx-auto" />
</div>
<p v-else-if="enrichedTemplates.length === 0" class="text-center mt-4">
No templates found.
</p>
<div v-else class="relative z-10">
<div class="grid grid-cols-1 mt-8 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8 sm:gap-y-12">
<single-template v-for="template in enrichedTemplates" :key="template.id" :slug="template.slug" />
</div>
</div>
</div>
</section>
</template>
<script>
import store from '~/store'
import { mapGetters, mapState } from 'vuex'
import Form from 'vform'
import Fuse from 'fuse.js'
import SingleTemplate from './SingleTemplate.vue'
const loadTemplates = function () {
store.commit('open/templates/startLoading')
store.dispatch('open/templates/loadIfEmpty').then(() => {
store.commit('open/templates/stopLoading')
})
}
export default {
name: 'TemplatesList',
components: { SingleTemplate },
props: {
onlyMy: {
type: Boolean,
required: false
}
},
data: () => ({
selectedType: 'all',
selectedIndustry: 'all',
searchTemplate: new Form({
search: ''
})
}),
watch: {},
mounted () {
loadTemplates()
},
computed: {
...mapState({
templates: state => state['open/templates'].content,
templatesLoading: state => state['open/templates'].loading,
industries: state => state['open/templates'].industries,
types: state => state['open/templates'].types
}),
...mapGetters({
user: 'auth/user'
}),
industriesOptions () {
return [{ name: 'All Industries', value: 'all' }].concat(Object.values(this.industries).map((industry) => {
return {
name: industry.name,
value: industry.slug
}
}))
},
typesOptions () {
return [{ name: 'All Types', value: 'all' }].concat(Object.values(this.types).map((type) => {
return {
name: type.name,
value: type.slug
}
}))
},
enrichedTemplates () {
let enrichedTemplates = (this.onlyMy && this.user) ? this.templates.filter((item) => { return item.creator_id === this.user.id}) : this.templates
// Filter by Selected Type
if (this.selectedType && this.selectedType !== 'all') {
enrichedTemplates = enrichedTemplates.filter((item) => {
return (item.types && item.types.length > 0) ? item.types.includes(this.selectedType) : false
})
}
// Filter by Selected Industry
if (this.selectedIndustry && this.selectedIndustry !== 'all') {
enrichedTemplates = enrichedTemplates.filter((item) => {
return (item.industries && item.industries.length > 0) ? item.industries.includes(this.selectedIndustry) : false
})
}
if (this.searchTemplate.search === '' || this.searchTemplate.search === null) {
return enrichedTemplates
}
// Fuze search
const fuzeOptions = {
keys: [
'name',
'slug',
'description',
'short_description'
]
}
const fuse = new Fuse(enrichedTemplates, fuzeOptions)
return fuse.search(this.searchTemplate.search).map((res) => {
return res.item
})
}
},
methods: {}
}
</script>

View File

@ -0,0 +1,44 @@
<template>
<div class="flex flex-col min-h-full border-t">
<section class="py-12 sm:py-16 bg-gray-50 border-b border-gray-200">
<div class="px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
<div class="text-center max-w-xl mx-auto">
<h1 class="text-3xl sm:text-4xl lg:text-5xl font-bold tracking-tight text-gray-900">
My Form Templates
</h1>
<p class="text-gray-600 mt-4 text-lg font-normal">
Share your best form as templates so that others can re-use them!
</p>
</div>
</div>
</section>
<templates-list :only-my="true" />
</div>
</template>
<script>
import TemplatesList from '../../components/pages/templates/TemplatesList.vue'
import SeoMeta from '../../mixins/seo-meta.js'
export default {
components: { TemplatesList },
mixins: [SeoMeta],
middleware: 'auth',
props: {
metaTitle: { type: String, default: 'My Templates' },
metaDescription: { type: String, default: 'Our collection of beautiful templates to create your own forms!' }
},
data () {
return {}
},
mounted () {},
computed: {},
methods: {}
}
</script>

View File

@ -2,7 +2,7 @@
<div class="flex flex-col min-h-full">
<breadcrumb :path="breadcrumbs">
<template #left>
<div v-if="user && (user.admin || user.template_editor)" class="ml-5">
<div v-if="canEditTemplate" class="ml-5">
<v-button color="gray" size="small" @click.prevent="showFormTemplateModal=true">
Edit Template
</v-button>
@ -12,6 +12,11 @@
</div>
</template>
<template #right>
<v-button v-if="canEditTemplate" v-track.copy_template_button_clicked size="small" color="white" class="mr-5"
@click.prevent="copyTemplateUrl"
>
Copy Template URL
</v-button>
<v-button v-track.use_template_button_clicked size="small" class="mr-5"
:to="{path: createFormWithTemplateUrl}"
>
@ -228,6 +233,16 @@ export default {
cleanQuotes (str) {
// Remove starting and ending quotes if any
return (str) ? str.replace(/^"/, '').replace(/"$/, '') : ''
},
copyTemplateUrl(){
const str = this.template.share_url
const el = document.createElement('textarea')
el.value = str
document.body.appendChild(el)
el.select()
document.execCommand('copy')
document.body.removeChild(el)
this.alertSuccess('Copied!')
}
},
@ -251,6 +266,9 @@ export default {
form () {
return this.template ? new Form(this.template.structure) : null
},
canEditTemplate () {
return this.user && this.template && (this.user.admin || this.user.template_editor || this.template.creator_id === this.user.id)
},
metaTitle () {
return this.template ? this.template.name : 'Form Template'
},

View File

@ -13,147 +13,34 @@
</div>
</section>
<section class="bg-white py-12 sm:py-16">
<div class="px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 sm:gap-6 relative z-20">
<div class="flex items-center gap-4">
<div class="flex-1 sm:flex-none">
<select-input v-model="selectedType" name="type"
:options="typesOptions" class="w-full sm:w-auto md:w-56"
/>
</div>
<div class="flex-1 sm:flex-none">
<select-input v-model="selectedIndustry" name="industry"
:options="industriesOptions" class="w-full sm:w-auto md:w-56"
/>
</div>
</div>
<div class="flex-1 w-full md:max-w-xs">
<text-input name="search" :form="searchTemplate" placeholder="Search..." />
</div>
</div>
<div v-if="templatesLoading" class="text-center mt-4">
<loader class="h-6 w-6 text-nt-blue mx-auto" />
</div>
<p v-else-if="enrichedTemplates.length === 0" class="text-center mt-4">
No templates found.
</p>
<div v-else class="relative z-10">
<div class="grid grid-cols-1 mt-8 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8 sm:gap-y-12">
<single-template v-for="template in enrichedTemplates" :key="template.id" :slug="template.slug" />
</div>
</div>
</div>
</section>
<templates-list />
<open-form-footer class="mt-8 border-t"/>
</div>
</template>
<script>
import store from '~/store'
import { mapGetters, mapState } from 'vuex'
import Form from 'vform'
import Fuse from 'fuse.js'
import SeoMeta from '../../mixins/seo-meta.js'
import OpenFormFooter from '../../components/pages/OpenFormFooter.vue'
import SingleTemplate from '../../components/pages/templates/SingleTemplate.vue'
const loadTemplates = function () {
store.commit('open/templates/startLoading')
store.dispatch('open/templates/loadIfEmpty').then(() => {
store.commit('open/templates/stopLoading')
})
}
import TemplatesList from '../../components/pages/templates/TemplatesList.vue'
import SeoMeta from '../../mixins/seo-meta.js'
export default {
components: { OpenFormFooter, SingleTemplate },
components: { OpenFormFooter, TemplatesList },
mixins: [SeoMeta],
beforeRouteEnter (to, from, next) {
loadTemplates()
next()
},
props: {
metaTitle: { type: String, default: 'Templates' },
metaDescription: { type: String, default: 'Our collection of beautiful templates to create your own forms!' }
},
data () {
return {
selectedType: 'all',
selectedIndustry: 'all',
searchTemplate: new Form({
search: ''
})
}
return {}
},
mounted () {
},
mounted () {},
computed: {
...mapState({
templates: state => state['open/templates'].content,
templatesLoading: state => state['open/templates'].loading,
industries: state => state['open/templates'].industries,
types: state => state['open/templates'].types
}),
industriesOptions () {
return [{ name: 'All Industries', value: 'all' }].concat(Object.values(this.industries).map((industry) => {
return {
name: industry.name,
value: industry.slug
}
}))
},
typesOptions () {
return [{ name: 'All Types', value: 'all' }].concat(Object.values(this.types).map((type) => {
return {
name: type.name,
value: type.slug
}
}))
},
enrichedTemplates () {
let enrichedTemplates = this.templates
// Filter by Selected Type
if (this.selectedType && this.selectedType !== 'all') {
enrichedTemplates = enrichedTemplates.filter((item) => {
return (item.types && item.types.length > 0) ? item.types.includes(this.selectedType) : false
})
}
// Filter by Selected Industry
if (this.selectedIndustry && this.selectedIndustry !== 'all') {
enrichedTemplates = enrichedTemplates.filter((item) => {
return (item.industries && item.industries.length > 0) ? item.industries.includes(this.selectedIndustry) : false
})
}
if (this.searchTemplate.search === '' || this.searchTemplate.search === null) {
return enrichedTemplates
}
// Fuze search
const fuzeOptions = {
keys: [
'name',
'slug',
'description',
'short_description'
]
}
const fuse = new Fuse(enrichedTemplates, fuzeOptions)
return fuse.search(this.searchTemplate.search).map((res) => {
return res.item
})
}
},
computed: {},
methods: {}
}

View File

@ -67,6 +67,7 @@ export default [
{ path: '/forms/:slug', name: 'forms.show_public', component: page('forms/show-public.vue') },
// Templates
{ path: '/my-templates', name: 'my_templates', component: page('templates/my_templates.vue') },
{ path: '/form-templates', name: 'templates', component: page('templates/templates.vue') },
{ path: '/form-templates/:slug', name: 'templates.show', component: page('templates/show.vue') },