Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Adicionar e Editar Widget do Bonde direto no plugin do CMS #140

Merged
merged 9 commits into from
Dec 8, 2023
21 changes: 15 additions & 6 deletions app/contrib/actions/pressure/cms_plugins.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from .forms import PressurePluginForm, PressureAjaxForm
from contrib.bonde.plugin_base import BondeWidgetPluginBase
from .forms import CreatePressurePluginForm, EditPressurePluginForm, PressureAjaxForm
from .models import PressurePluginModel


@plugin_pool.register_plugin
class PressurePlugin(CMSPluginBase):
class PressurePlugin(BondeWidgetPluginBase):
name = "Pressão"
module = "Estrategia"
render_template = "pressure/pressure_plugin.html"
model = PressurePluginModel
form = PressurePluginForm
cache = False
edit_form_class = EditPressurePluginForm
add_form_class = CreatePressurePluginForm
fieldsets = [
(
"Pressão por e-mail",
{
"fields": ["targets", "pressure_email_subject", "pressure_email_content"],
},
),
]

def render(self, context, instance, placeholder):
obj = instance.get_widget()
obj = instance.widget
request = context["request"]
initial = (
{
Expand All @@ -29,7 +38,7 @@ def render(self, context, instance, placeholder):
form = PressureAjaxForm(initial=initial)

if instance.reference_id:
scheme = request.scheme if request.scheme else 'https'
scheme = request.scheme if request.scheme else "https"
url = f"{scheme}://{request.get_host()}{request.path}"

form = PressureAjaxForm(
Expand Down
84 changes: 80 additions & 4 deletions app/contrib/actions/pressure/forms.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,99 @@
import json
import jwt
import re
import requests

from django import forms
from django.conf import settings

from contrib.bonde.forms import ReferenceBaseModelForm
from contrib.bonde.models import WidgetKind
from contrib.bonde.forms import ChangeReferenceBaseModelForm, CreateReferenceBaseModelForm
from tailwind.forms import StyledBaseForm

from .models import PressurePluginModel


class PressurePluginForm(ReferenceBaseModelForm):
action_kind = "pressure"
class ArrayWidget(forms.TextInput):
class Media:
css = {
"all": [
"//cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css",
]
}
js = [
"//cdn.jsdelivr.net/npm/@yaireo/tagify/dist/jQuery.tagify.min.js",
"pressure/js/array-widget.js",
]

class Meta(ReferenceBaseModelForm.Meta):
def __init__(self, attrs={}):
classes = attrs.get("class", None)
attrs = {
**attrs,
"class": classes + " array-widget" if classes else "array-widget",
}

super().__init__(attrs=attrs)


class CreatePressurePluginForm(CreateReferenceBaseModelForm):
# Settings Widget Kind Form
action_kind = WidgetKind.pressure

class Meta(CreateReferenceBaseModelForm.Meta):
abstract = False
model = PressurePluginModel


class EditPressurePluginForm(ChangeReferenceBaseModelForm):
# Settings Widget Kind Form
action_kind = WidgetKind.pressure

# Extra fields
targets = forms.CharField(
label="Alvos",
widget=ArrayWidget(attrs={"placeholder": "Nome do alvo: <[email protected]>"}),
help_text="Escreva nome e e-mail do alvo desta forma: \"Nome do alvo &lt;[email protected]&gt;\" e pressione ENTER."
)

pressure_email_subject = forms.CharField(
label="Assunto do e-mail de pressão", required=False
)
pressure_email_content = forms.CharField(
label="Corpo do e-mail de pressão", widget=forms.Textarea, required=False
)

class Meta(ChangeReferenceBaseModelForm.Meta):
abstract = False
model = PressurePluginModel

def prepare_fields(self):
super().prepare_fields()

obj = self.instance.widget
self.fields["pressure_email_subject"].initial = obj.settings.get(
"pressure_subject"
)
self.fields["pressure_email_content"].initial = obj.settings.get(
"pressure_body"
)

self.fields["targets"].initial = ",".join(obj.settings.get("targets"))

def update_widget_settings(self, widget, commit=True):
widget = super().update_widget_settings(widget, commit=False)

widget.settings["pressure_subject"] = self.cleaned_data[
"pressure_email_subject"
]
widget.settings["pressure_body"] = self.cleaned_data["pressure_email_content"]

widget.settings["targets"] = list(map(lambda x: x['value'], json.loads(self.cleaned_data["targets"])))

if commit:
widget.save()

return widget


class PressureAjaxForm(StyledBaseForm):
reference_id = forms.IntegerField(widget=forms.HiddenInput)
Expand Down
21 changes: 5 additions & 16 deletions app/contrib/actions/pressure/models.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,11 @@
from django.db import models
# from django.db import models

from cms.models import CMSPlugin
# from cms.models import CMSPlugin

from contrib.bonde.models import Widget
from contrib.bonde.models import BondeBasePluginModel


class PressurePluginModel(CMSPlugin):
class PressurePluginModel(BondeBasePluginModel):
"""
"""
reference_id = models.IntegerField(
null=True,
blank=True,
help_text="ID de referência da widget na plataforma Bonde"
)


def get_widget(self) -> Widget | None:
if not self.reference_id:
return None

return Widget.objects.get(id=self.reference_id)
pass
17 changes: 17 additions & 0 deletions app/contrib/actions/pressure/static/bonde/css/edit-widget-form.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
.tabs {
display: flex;
flex-direction: row;
}

.tabs > h2 {
cursor: pointer;
padding: 10px 20px 5px 5px;
}

.tabs > .tab-active {
border-bottom: 2px solid black;
}

.tabs-content > fieldset {
padding: 25px 0 !important;
}
42 changes: 42 additions & 0 deletions app/contrib/actions/pressure/static/bonde/js/edit-widget-form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
(function ($) {
"use strict";

$(function () {
let actived = 0;

function toggle(index) {
if (index == actived) {
$(".tabs-content > fieldset").eq(index).show();
} else {
$(".tabs-content > fieldset").hide();
$(".tabs > h2").removeClass("tab-active");

$(".tabs > h2").eq(index).addClass("tab-active");
$(".tabs-content > fieldset").eq(index).show();
}
actived = index
}

// Cria estrutura básica para tabs
$("fieldset").eq(0).before('<div class="tabs"></div>');
$("fieldset").eq(0).before('<div class="tabs-content"></div>');

$(".tabs").append($("fieldset > h2").detach());
$(".tabs-content").append($("fieldset").detach());

// Adiciona eventos
$(".tabs > h2").each(function(index) {
// Default is first open
if (index !== 0) {
$(".tabs-content > fieldset").eq(index).hide();
} else {
$(".tabs > h2").eq(index).addClass("tab-active");
}

$(".tabs > h2").eq(index).on("click", function() {
toggle(index)
// $(".tabs-content > fieldset").eq(index).show();
});
});
});
}(window.jQuery));
49 changes: 49 additions & 0 deletions app/contrib/actions/pressure/static/pressure/js/array-widget.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
(function ($) {
"use strict";

const patternTargetEmail = /[a-zà-úA-ZÀ-Ú\s]+<(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))>/

// function validate (value) {
// const patternTargetEmail = /[a-zà-úA-ZÀ-Ú\s]+<(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))>/
// return patternTargetEmail.test(value)
// }

// function add (value) {
// const name = value.split("<")[0].trim();
// const email = value.split("<")[1].trim().replace(">", "");

// console.log({ name, email });
// $("input.array-widget").after("<p>" + name + " " + email + "</p>");
// }

miguelzinh3 marked this conversation as resolved.
Show resolved Hide resolved

$(function () {
$("input.array-widget")
.tagify({
pattern: patternTargetEmail
})
.on("add", function (e, tagData) {
console.log("add", { e, tagData });
})
.on("remove", function(e, tagData) {
console.log("remove", { e, tagData });
})
.on("invalid", function(e, tagData) {
console.log("invalid", { e, tagData });
});

$("input.array-widget").on("change", function (evt) {
console.log(evt.target)
});
// $("input.array-widget").on("keydown", function(evt) {
// if (evt.originalEvent.code === "Slash") {
// console.log("processa a tag")

// console.log("validate", validate(evt.target.value))
// if (validate(evt.target.value)) {
// add(evt.target.value)
// }
// }
// });
miguelzinh3 marked this conversation as resolved.
Show resolved Hide resolved
});
}(window.jQuery));
6 changes: 4 additions & 2 deletions app/contrib/actions/pressure/static/pressure/js/pressure.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@
}

function doneResponse({ success, html }) {
$("#pressureWrapper").empty();
$("#pressureWrapper").html(html);
var instanceId = $('.pressure-plugin').data('instance-id');

$('#pressureWrapper-' + instanceId).empty();
$('#pressureWrapper-' + instanceId).html(html);

$("#copyToClipboard").on("click", function () {
const textToCopy = window.location.href;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
{% addtoblock "css" %}
{% if settings.main_color %}
<style>
#pressureWrapper h3 {
#pressureWrapper-{{instance.id}} h3 {
color: {{ settings.main_color }};
}
#pressureForm input:focus, #pressureForm textarea:focus {
#pressureWrapper-{{instance.id}} #pressureForm input:focus,
#pressureWrapper-{{instance.id}} #pressureForm textarea:focus {
border: 1px solid {{ settings.main_color }};
}
#pressureForm button[type="submit"] {
#pressureWrapper-{{instance.id}} #pressureForm button[type="submit"] {
color: white;
background-color: {{ settings.main_color }};
}
#pressureForm .counter {
#pressureWrapper-{{instance.id}} #pressureForm .counter {
color: {{ settings.main_color }};
}
</style>
Expand All @@ -25,7 +26,7 @@
<script type="text/javascript" src="{% static 'pressure/js/pressure.js' %}"></script>
{% endaddtoblock %}

<div id="pressureWrapper" class="container pressure-plugin plugin">
<div id="pressureWrapper-{{instance.id}}" data-instance-id="{{ instance.id }}" class="container pressure-plugin plugin">
<div class="bg-white rounded-lg">
<h3 class="px-4 pt-4 text-lg font-bold text-center mb-2">{{settings.title}}</h3>
<div class="px-6 py-4 bg-gray-200">
Expand Down
Loading
Loading