Add crud for promos, discountapply name value collection

This commit is contained in:
Ramon Gutierrez 2018-02-01 15:07:43 +08:00
parent f004294dbc
commit 2ec8a369f6
8 changed files with 764 additions and 0 deletions

View file

@ -208,3 +208,17 @@ access_keys:
label: Update
- id: ticket.delete
label: Delete
- id: promo
label: Promo Access
acls:
- id: promo.menu
label: Menu
- id: promo.list
label: List
- id: promo.add
label: Add
- id: promo.update
label: Update
- id: promo.delete
label: Delete

View file

@ -28,6 +28,10 @@ main_menu:
acl: rider.list
label: Riders
parent: database
- id: promo_list
acl: promo.list
label: Promos
parent: database
- id: battery
acl: battery.menu

36
config/routes/promo.yaml Normal file
View file

@ -0,0 +1,36 @@
# promo
promo_list:
path: /promos
controller: App\Controller\PromoController::index
promo_rows:
path: /promos/rows
controller: App\Controller\PromoController::rows
methods: [POST]
promo_create:
path: /promos/create
controller: App\Controller\PromoController::addForm
methods: [GET]
promo_create_submit:
path: /promos/create
controller: App\Controller\PromoController::addSubmit
methods: [POST]
promo_update:
path: /promos/{id}
controller: App\Controller\PromoController::updateForm
methods: [GET]
promo_update_submit:
path: /promos/{id}
controller: App\Controller\PromoController::updateSubmit
methods: [POST]
promo_delete:
path: /promos/{id}
controller: App\Controller\PromoController::destroy
methods: [DELETE]

View file

@ -0,0 +1,273 @@
<?php
namespace App\Controller;
use App\Ramcar\BaseController;
use App\Ramcar\DiscountApply;
use App\Entity\Promo;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use DateTime;
class PromoController extends BaseController
{
public function index()
{
$this->denyAccessUnlessGranted('promo.list', null, 'No access.');
$params = $this->initParameters('promo_list');
return $this->render('promo/list.html.twig', $params);
}
public function rows(Request $req)
{
$this->denyAccessUnlessGranted('promo.list', null, 'No access.');
// get query builder
$qb = $this->getDoctrine()
->getRepository(Promo::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)');
$this->setQueryFilters($datatable, $tquery);
$total = $tquery->getQuery()
->getSingleScalarResult();
// get current page number
$page = $datatable['pagination']['page'] ?? 1;
$perpage = $datatable['pagination']['perpage'];
$offset = ($page - 1) * $perpage;
// add metadata
$meta = [
'page' => $page,
'perpage' => $perpage,
'pages' => ceil($total / $perpage),
'total' => $total,
'sort' => 'asc',
'field' => 'id'
];
// build query
$query = $qb->select('q');
$this->setQueryFilters($datatable, $query);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy('q.' . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
$discount_apply = DiscountApply::getCollection();
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['name'] = $orow->getName();
$row['code'] = $orow->getCode();
$row['discount_rate'] = ($orow->getDiscountRate() * 100) . '%';
$row['discount_apply'] = $discount_apply[$orow->getDiscountApply()];
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('promo.update'))
$row['meta']['update_url'] = $this->generateUrl('promo_update', ['id' => $row['id']]);
if ($this->isGranted('promo.delete'))
$row['meta']['delete_url'] = $this->generateUrl('promo_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
protected function setObject(Promo $obj, Request $req)
{
// set and save values
$obj->setName($req->request->get('name'))
->setCode($req->request->get('code'))
->setDiscountRate($req->request->get('discount_rate'))
->setDiscountApply($req->request->get('discount_apply'));
}
protected function setQueryFilters($datatable, QueryBuilder $query)
{
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.name LIKE :filter')
->orWhere('q.code LIKE :filter')
->orWhere('q.discount_rate LIKE :filter')
->orWhere('q.discount_apply LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
public function addForm()
{
$this->denyAccessUnlessGranted('promo.add', null, 'No access.');
$params = $this->initParameters('promo_list');
$params['obj'] = new Promo();
$params['mode'] = 'create';
$params['discount_apply'] = DiscountApply::getCollection();
// response
return $this->render('promo/form.html.twig', $params);
}
public function addSubmit(Request $req, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('promo.add', null, 'No access.');
// create new object
$em = $this->getDoctrine()->getManager();
$obj = new Promo();
$this->setObject($obj, $req);
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->persist($obj);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
public function updateForm($id)
{
$this->denyAccessUnlessGranted('promo.update', null, 'No access.');
$params = $this->initParameters('promo_list');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Promo::class)->find($id);
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$params['obj'] = $obj;
$params['mode'] = 'update';
$params['discount_apply'] = DiscountApply::getCollection();
// response
return $this->render('promo/form.html.twig', $params);
}
public function updateSubmit(Request $req, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('promo.update', null, 'No access.');
// get object data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Promo::class)->find($id);
// make sure this object exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$this->setObject($obj, $req);
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
public function destroy($id)
{
$this->denyAccessUnlessGranted('promo.delete', null, 'No access.');
$params = $this->initParameters('promo_list');
// get objext data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Promo::class)->find($id);
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
// delete this object
$em->remove($obj);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
}

102
src/Entity/Promo.php Normal file
View file

@ -0,0 +1,102 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="promo")
* @UniqueEntity("code")
*/
class Promo
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// name
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $name;
// code
/**
* @ORM\Column(type="string", length=80, unique=true)
* @Assert\NotBlank()
*/
protected $code;
// discount rate (multiplier)
/**
* @ORM\Column(type="decimal", precision=11, scale=10)
* @Assert\NotBlank()
* @Assert\Range(min=0, minMessage="This value should be a valid number.")
*/
protected $discount_rate;
// price discount applies to
/**
* @ORM\Column(type="string", length=10)
* @Assert\NotBlank()
*/
protected $discount_apply;
public function getID()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setCode($code)
{
$this->code = $code;
return $this;
}
public function getCode()
{
return $this->code;
}
public function setDiscountRate($discount_rate)
{
$this->discount_rate = $discount_rate;
return $this;
}
public function getDiscountRate()
{
return $this->discount_rate;
}
public function setDiscountApply($discount_apply)
{
$this->discount_apply = $discount_apply;
return $this;
}
public function getDiscountApply()
{
return $this->discount_apply;
}
}

View file

@ -0,0 +1,14 @@
<?php
namespace App\Ramcar;
class DiscountApply extends NameValue
{
const SRP = 'srp';
const OPL = 'opl';
const COLLECTION = [
'srp' => 'SRP',
'opl' => 'OPL',
];
}

View file

@ -0,0 +1,160 @@
{% extends 'base.html.twig' %}
{% block body %}
<!-- BEGIN: Subheader -->
<div class="m-subheader">
<div class="d-flex align-items-center">
<div class="mr-auto">
<h3 class="m-subheader__title">Promos</h3>
</div>
</div>
</div>
<!-- END: Subheader -->
<div class="m-content">
<!--Begin::Section-->
<div class="row">
<div class="col-xl-12">
<div class="m-portlet m-portlet--mobile">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon">
<i class="fa fa-building"></i>
</span>
<h3 class="m-portlet__head-text">
{% if mode == 'update' %}
Edit Promo
<small>{{ obj.getName }}</small>
{% else %}
New Promo
{% endif %}
</h3>
</div>
</div>
</div>
<form id="row-form" class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" method="post" action="{{ mode == 'update' ? url('promo_update_submit', {'id': obj.getId}) : url('promo_create_submit') }}">
<div class="m-portlet__body">
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label for="name" data-field="name">
Name
</label>
<input type="text" name="name" class="form-control m-input" value="{{ obj.getName }}">
<div class="form-control-feedback hide" data-field="name"></div>
</div>
<div class="col-lg-6">
<label for="code" data-field="code">
Code
</label>
<input type="text" name="code" class="form-control m-input" value="{{ obj.getCode }}">
<div class="form-control-feedback hide" data-field="code"></div>
</div>
</div>
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label for="discount_rate" data-field="discount_rate">
Discount Rate
</label>
<input type="number" name="discount_rate" class="form-control m-input" step="any" value="{{ obj.getDiscountRate|trim('0', 'right') }}">
<div class="form-control-feedback hide" data-field="discount_rate"></div>
</div>
<div class="col-lg-6">
<label for="discount_apply" data-field="discount_apply">
Discount Apply
</label>
<select name="discount_apply" class="form-control m-input">
{% for key, discount in discount_apply %}
<option value="{{ key }}"{{ obj.getDiscountApply == key ? ' selected' }}>{{ discount }}</option>
{% endfor %}
</select>
<div class="form-control-feedback hide" data-field="discount_apply"></div>
</div>
</div>
</div>
<div class="m-portlet__foot m-portlet__foot--fit">
<div class="m-form__actions m-form__actions--solid m-form__actions--right">
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-success">Submit</button>
<a href="{{ url('promo_list') }}" class="btn btn-secondary">Cancel</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
$(function() {
$("#row-form").submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
method: "POST",
url: form.prop('action'),
data: form.serialize()
}).done(function(response) {
// remove all error classes
removeErrors();
swal({
title: 'Done!',
text: 'Your changes have been saved!',
type: 'success',
onClose: function() {
window.location.href = "{{ url('promo_list') }}";
}
});
}).fail(function(response) {
var errors = response.responseJSON.errors;
var firstfield = false;
// remove all error classes first
removeErrors();
// display errors contextually
$.each(errors, function(field, msg) {
var formfield = $("[name='" + field + "']");
var label = $("label[data-field='" + field + "']");
var msgbox = $(".form-control-feedback[data-field='" + field + "']");
// add error classes to bad fields
formfield.addClass('form-control-danger');
label.addClass('has-danger');
msgbox.html(msg).addClass('has-danger').removeClass('hide');
// check if this field comes first in DOM
var domfield = formfield.get(0);
if (!firstfield || (firstfield && firstfield.compareDocumentPosition(domfield) === 2)) {
firstfield = domfield;
}
});
// focus on first bad field
firstfield.focus();
// scroll to above that field to make it visible
$('html, body').animate({
scrollTop: $(firstfield).offset().top - 200
}, 100);
});
});
// remove all error classes
function removeErrors() {
$(".form-control-danger").removeClass('form-control-danger');
$("[data-field]").removeClass('has-danger');
$(".form-control-feedback[data-field]").addClass('hide');
}
});
</script>
{% endblock %}

View file

@ -0,0 +1,161 @@
{% extends 'base.html.twig' %}
{% block body %}
<!-- BEGIN: Subheader -->
<div class="m-subheader">
<div class="d-flex align-items-center">
<div class="mr-auto">
<h3 class="m-subheader__title">
Promos
</h3>
</div>
</div>
</div>
<!-- END: Subheader -->
<div class="m-content">
<!--Begin::Section-->
<div class="row">
<div class="col-xl-12">
<div class="m-portlet m-portlet--mobile">
<div class="m-portlet__body">
<div class="m-form m-form--label-align-right m--margin-top-20 m--margin-bottom-30">
<div class="row align-items-center">
<div class="col-xl-8 order-2 order-xl-1">
<div class="form-group m-form__group row align-items-center">
<div class="col-md-4">
<div class="m-input-icon m-input-icon--left">
<input type="text" class="form-control m-input m-input--solid" placeholder="Search..." id="data-rows-search">
<span class="m-input-icon__icon m-input-icon__icon--left">
<span><i class="la la-search"></i></span>
</span>
</div>
</div>
</div>
</div>
<div class="col-xl-4 order-1 order-xl-2 m--align-right">
<a href="{{ url('promo_create') }}" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
<span>
<i class="la la-star-o"></i>
<span>New Promo</span>
</span>
</a>
<div class="m-separator m-separator--dashed d-xl-none"></div>
</div>
</div>
</div>
<!--begin: Datatable -->
<div id="data-rows"></div>
<!--end: Datatable -->
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
$(function() {
var options = {
data: {
type: 'remote',
source: {
read: {
url: '{{ url("promo_rows") }}',
method: 'POST',
}
},
saveState: {
cookie: false,
webstorage: false
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
columns: [
{
field: 'id',
title: 'ID',
width: 30
},
{
field: 'name',
title: 'Name'
},
{
field: 'code',
title: 'Code'
},
{
field: 'discount_rate',
title: 'Discount Rate'
},
{
field: 'discount_apply',
title: 'Applies To'
},
{
field: 'Actions',
width: 110,
title: 'Actions',
sortable: false,
overflow: 'visible',
template: function (row, index, datatable) {
var actions = '';
if (row.meta.update_url != '') {
actions += '<a href="' + row.meta.update_url + '" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill btn-edit" data-id="' + row.name + '" title="Edit"><i class="la la-edit"></i></a>';
}
if (row.meta.delete_url != '') {
actions += '<a href="' + row.meta.delete_url + '" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill btn-delete" data-id="' + row.name + '" title="Delete"><i class="la la-trash"></i></a>';
}
return actions;
},
}
],
search: {
onEnter: false,
input: $('#data-rows-search'),
delay: 400
}
};
var table = $("#data-rows").mDatatable(options);
$(document).on('click', '.btn-delete', function(e) {
var url = $(this).prop('href');
var id = $(this).data('id');
var btn = $(this);
e.preventDefault();
swal({
title: 'Confirmation',
html: 'Are you sure you want to delete <strong>' + id + '</strong>?',
type: 'warning',
showCancelButton: true
}).then((result) => {
if (result.value) {
$.ajax({
method: "DELETE",
url: url
}).done(function(response) {
table.row(btn.parents('tr')).remove();
table.reload();
}).fail(function() {
swal({
title: 'Whoops',
text: 'An error occurred while deleting this item. Please contact support.',
type: 'error'
});
});
}
});
});
});
</script>
{% endblock %}