More sort routes

This commit is contained in:
Brian Read 2024-04-28 12:03:06 +01:00
parent b96239639c
commit 26e9889061
15 changed files with 549 additions and 235 deletions

View File

@ -2,13 +2,8 @@
# Routines to be editted by the developer to provide validation for parameters
# and provison of the control data for table(s)
#
# Generated by SM2Gen version:${version}
# Generated by SME2Gen version:0.6 Chameleon version:4.5.4 On Python:3.10.12 at 2024-04-27 10:35
#
#$cdb=$main::cdb;
#$adb=$main::adb;
#$ndb=$main::ndb;
#$hdb=$main::hdb;
#$ddb=$main::ddb;
use esmith::util;
use esmith::HostsDB;
@ -28,11 +23,13 @@ our $ddb = esmith::DomainsDB->open() || die("Couldn't open Domains db");
# Validation routines - parameters for each panel
sub validate_PARAMS {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
sub validate_TABLE {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
@ -40,19 +37,70 @@ our $ddb = esmith::DomainsDB->open() || die("Couldn't open Domains db");
# Get control data for tables(s)
sub get_ibays {
sub get_ibays {
my $c = shift;
my @res;
my @ibays = $adb->ibays();
foreach my $i (@ibays){
my %hash = ('Name'=> $i->prop('Name'),
'Description' => $i->prop('Description'),
'Flag' => 1,
'PARAMS' => 'Modify'
# Taken pretty well verbatim from /usr/share/perl5/vendor_perl/esmith/FormMagick/Panel/nfsshare.pm
# although the href is more specific to the SM2 structure.
my $ibayname = $i->key();
my $ibaydesc = $i->prop('Name');
my $ibaynfs = $i->prop('NfsStatus')||'disabled';
my $modifiable = $i->prop('Modifiable') || 'yes';
$ibaynfs = $c->l('ENABLED') if ($ibaynfs eq 'enabled');
$ibaynfs = $c->l('DISABLED') if ($ibaynfs eq 'disabled');
#my $params = $self->build_ibay_cgi_params($ibayname, $i->props());
#my $scriptname = "nfsshareu";
#my $href = "$scriptname?$params&action=modify&wherenext=";
my $actionModify = ' ';
if ($modifiable eq 'yes'){
$actionModify .= "<a href='nfsshareu?trt=PARAMS&IbayName=$ibayname'><button class='sme-modify-button' title=".$c->l("MODIFY").">".$c->l("MODIFY")."</button></a>"."&nbsp"
}
my %hash = ('Name'=> $ibayname,
'Description' => $ibaydesc,
'Flag' => $ibaynfs,
'Modify' => $actionModify
);
push(@res,\%hash);
}
return \@res
}
}
# Return hash with values from row in which link clicked on table
sub validate_get_selected_PARAMS {
$selected = shift; #Parameter is name of selected row.
%ret = {};
return $ret;
}
sub validate_get_selected_TABLE {
$selected = shift; #Parameter is name of selected row.
%ret = {};
return $ret;
}
#after sucessful modify or create or whatever and submit then perfom (if the params validate)
sub perform_PARAMS {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
sub perform_TABLE {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
1;

View File

@ -2,11 +2,8 @@
# Routines to be editted by the developer to provide validation for parameters
# and provison of the control data for table(s)
#
#$cdb=$main::cdb;
#$adb=$main::adb;
#$ndb=$main::ndb;
#$hdb=$main::hdb;
#$ddb=$main::ddb;
# Generated by SME2Gen version:0.6 Chameleon version:4.5.4 On Python:3.10.12 at 2024-04-28 11:53
#
use esmith::util;
use esmith::HostsDB;
@ -26,11 +23,13 @@ our $ddb = esmith::DomainsDB->open() || die("Couldn't open Domains db");
# Validation routines - parameters for each panel
sub validate_PARAMS {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
sub validate_TABLE {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
@ -38,9 +37,42 @@ our $ddb = esmith::DomainsDB->open() || die("Couldn't open Domains db");
# Get control data for tables(s)
sub get_ibays {
return []
}
sub get_ibays {
my $c = shift;
@ret = {}
return \@ret
}
# Return hash with values from row in which link clicked on table
sub validate_get_selected_PARAMS {
$selected = shift; #Parameter is name of selected row.
%ret = {};
return $ret;
}
sub validate_get_selected_TABLE {
$selected = shift; #Parameter is name of selected row.
%ret = {};
return $ret;
}
#after sucessful modify or create or whatever and submit then perfom (if the params validate)
sub perform_PARAMS {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
sub perform_TABLE {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
1;

View File

@ -1,4 +1,7 @@
% layout 'default', title => "Sme server 2 - NFS data share", share_dir => './';
%#
%# Generated by SME2Gen version:0.6 Chameleon version:4.5.4 On Python:3.10.12 at 2024-04-28 11:53
%#
% content_for 'module' => begin
<div id="module" class="module Nfsshare-panel">

View File

@ -1,49 +1,25 @@
package SrvMngr::Controller::Nfsshare;
#
# Generated by version:SME2Gen version:0.6 Chameleon version:4.5.4 On Python:3.10.12 at 2024-04-28 11:53
#
#----------------------------------------------------------------------
# heading : Network
# description : NFS data share
# navigation : 2000 400
#
# name : nfsshare, method : get, url : /nfsshare, ctlact : nfsshare#main
# name : nfsshared, method : post, url : /nfsshared, ctlact : nfsshare#do_update
# name : nfsshareu, method : post, url : /nfsshareu, ctlact : nfsshare#do_update
# name : nfsshared, method : get, url : /nfsshared, ctlact : nfsshare#do_display
#
# routes : end
#
# Documentation: https://wiki.contribs.org/{PackageName}
# Documentation: https://wiki.contribs.org/Nfsshare
#----------------------------------------------------------------------
#
# Scheme of things:
#
#main:
##
## Initial entry
##
#set initial panel
#for initial panel:
# load up _data hash with DB fields
# load up stash with pointer(s) to control fields hash(= get-))
#render initial panel
#
#do_display
##
## Return after submit pushed on panel
##
#load up all params into local hash
# by panel:
# by param:
# validate param (return ret = ok or error message) - call validate-
# break out on error
#if validation not ok
# render back to current panel with error message in stash
#otherwise
# By panel:
# Copy back to DB any that have changed (how to easily tell if it has changed?)
# do whatever is required (inc signal_event smeserver-<whatever>-update?)
# set success
# call main?
# TBA!!
use strict;
use warnings;
@ -76,6 +52,16 @@ our $ddb = esmith::DomainsDB->open() || die("Couldn't open Domains db");
require '/usr/share/smanager/lib/SrvMngr/Controller/Nfsshare-Custom.pm'; #The code that is to be added by the developer
sub main {
#
# Initial entry - route is "/<whatever>"
#
#set initial panel
#for initial panel:
#Specifiy panel to enter
#load up _data hash with DB fields
#load up stash with pointer(s) to control fields hash(= get-))
#and a pointer to the prefix_data hash
#render initial panel
my $c = shift;
$c->app->log->info( $c->log_req );
@ -87,12 +73,12 @@ sub main {
$nfs_data{'trt'} = 'TABLE';
#Load any DB entries into the <prefix>_data area so as they are preset in the form
# which DB
# which DB - this only really works if the initial panel is a PARAMS type panel and not a TABLE
my $db = $cdb; #pickup local or global db or Default to config
# and table control fields
$c->stash(ibays=>get_ibays());
$c->stash(ibays=>get_ibays($c));
$c->stash(
@ -103,7 +89,32 @@ sub main {
$c->render( template => "Nfsshare" );
}
# Post request with params - submit from a form
sub do_update {
#
# Return after submit pushed on panel (this is a post) - route is "/<whatever>u"
# parameters in the params hash.
#
#load up all params into prefix_data hash:
#By panel (series of if statements - only one executed):
#call validate-PANEL() - return ret = ok or error message
#if validation not ok:
#render back to current panel with error message in stash
#otherwise:
#By panel (series of if statements - only one executed):
#do whatever is required: call perform-PANEL() - return "ok" or Error Message
#call signal-event for any global actions specified (check it exists - error and continue?)
#if action smeserver-<whatever>-update exists
#signal_event smeserver-<whatever>-update
#call signal-event for any specific actions for thids panel (check it exists first - error and continue)
#set success in stash
#if no "nextpanel" entry:
#set firstpanel
#else
#set nextpanel
#call render
my $c = shift;
$c->app->log->info($c->log_req);
@ -116,49 +127,137 @@ sub do_update {
# Get number of POST parameters
my $num_params = keys %params;
#Params are available in the hash "params"
# you may use:
my @result;
foreach my $key (keys %params) {
my $value = $params{$key};
push @result, { $key => $value };
$c->app->log->debug("$key: $value");
#Params are available in the hash "params" - copy to the prefix_data hash
while (my ($key, $value) = each %{$c->req->params->to_hash}) {
$nfs_data{$key} = $value;
}
# the value of trt will tell you which panel has returned
my $trt = $c->param('trt') || 'TABLE' ; #hidden control on every form.
my $trt = $c->param('trt') || 'TABLE'; #hidden control on every form.
my $ret = 'ok';
#Validate the parameters accordingly
#Validate the parameters in a custom sub one for each panel (although only one of these will be executed)
my $thispanel;
if ($trt eq 'PARAMS'){
#Validate form parameters for panel PARAMS
$ret = validate_PARAMS();
$ret = validate_PARAMS(\%nfs_data);
$thispanel = 'PARAMS';
}
if ($trt eq 'TABLE'){
#Validate form parameters for panel TABLE
$ret = validate_TABLE();
$ret = validate_TABLE(\%nfs_data);
$thispanel = 'TABLE';
}
if ($ret eq "ok") {
#Do whatever is needed, including writing values to the DB
my $db = $cdb; #pickup local or global db or Default to config
# anything else here...
$c->stash( success => $c->l("$thispanel successfull message"));
if ($ret ne "ok") {
# return to the panel with error message
$c->stash(error => $c->l($ret));
$c->render("Nfsshare");
} else {
#Do whatever is needed, including writing values to the DB
if ($trt eq 'PARAMS'){
#do whatever is required ...
$ret = perform_PARAMS(\%nfs_data);
if ($ret ne "ok") {
# return to the panel with error message
$c->stash(error => $c->l($ret));
$c->render("Nfsshare");
} else {
$c->stash( success => $c->l("PARAMS panel action was successfull")); #A bit bland - edit it in the lex file
}
}
if ($trt eq 'TABLE'){
#do whatever is required ...
$ret = perform_TABLE(\%nfs_data);
if ($ret ne "ok") {
# return to the panel with error message
$c->stash(error => $c->l($ret));
$c->render("Nfsshare");
} else {
$c->stash( success => $c->l("TABLE panel action was successfull")); #A bit bland - edit it in the lex file
}
}
# and call any signal-events needed
# Setup shared data and call panel
$c->stash(
title => $title,
nfs_data => \%nfs_data
# Extra data in here - repeat for each stash data entry needed for panels
);
nfs_data{'trt'} = 'TABLE';
if ('none' eq 'none') {
$nfs_data{'trt'} = 'TABLE';
} else {
$nfs_data{'trt'} = 'none';
}
$c->render("Nfsshare");
}
}
sub do_display {
#
# Return after link clicked in table (this is a get) - route is "/<whatever>d"
# Expects ?trt=PANEL&selected="TableRowName" plus any other required
#
#load up all supplied params into prefix_data hash
#call get-selected-PANEL() - returns hash of all relevent parameters
#load up returned hash into prefix_data
#render - to called panel
my $c = shift;
$c->app->log->info($c->log_req);
my %nfs_data = ();
my $title = $c->l("nfs_NFS data share");
# Accessing all POST parameters
my %params = $c->req->params->to_hash;
# Get number of POST parameters
my $num_params = keys %params;
#Params are available in the hash "params" - copy to the prefix_data hash
while (my ($key, $value) = each %{$c->req->params->to_hash}) {
$nfs_data{$key} = $value;
}
# the value of trt will tell you which panel has returned
my $trt = $c->param('trt') || 'TABLE'; #Indicates where to go now
# Now add in the params from the selected row from the table
my %selectedrow;
if ($trt eq 'PARAMS'){
#Validate form parameters for panel PARAMS
%selectedrow = selected_PARAMS($nfs_data{'Selected'});
}
if ($trt eq 'TABLE'){
#Validate form parameters for panel TABLE
%selectedrow = selected_TABLE($nfs_data{'Selected'});
}
#Copy in the selected row params to the prefix_data hash to pass to the panel
while (my ($key, $value) = each %selectedrow){
$nfs_data{$key} = $value;
}
# Where to go now
$nfs_data{'trt'} = $trt;
# Data for panel
$c->stash(
title => $title,
nfs_data => \%nfs_data
);
$c->render("Nfsshare");
}
1;

View File

@ -1,3 +1,6 @@
%#
%# Generated by SME2Gen version:0.6 Chameleon version:4.5.4 On Python:3.10.12 at 2024-04-28 11:53
%#
<div id="Nfsshare-PARAMS">
<script>
window.onload = function() {
@ -13,7 +16,9 @@
% param 'trt' => $nfs_data->{trt} unless param 'trt';
%= hidden_field 'trt' => $nfs_data->{trt}
%# Inputs etc in here.
<h2>Manage NFS Ibay settings:</h2>
<h2>Manage NFS Ibay settings:</h2>
<p>
%= l('nfs_These parameters will be effective only if the share is enabled. The share is in /home/e-smith/files/ibays//files')
</p>

View File

@ -1,3 +1,6 @@
%#
%# Generated by SME2Gen version:0.6 Chameleon version:4.5.4 On Python:3.10.12 at 2024-04-28 11:53
%#
<div id="Nfsshare-TABLE">
<script>
window.onload = function() {
@ -13,8 +16,10 @@
% param 'trt' => $nfs_data->{trt} unless param 'trt';
%= hidden_field 'trt' => $nfs_data->{trt}
%# Inputs etc in here.
<h2>Manage NFS Ibay settings:</h2>
<table class="sme-border TableSort">
<h2>Manage NFS Ibay settings:</h2>
<br /><table class="sme-border TableSort">
<thead>
<tr>
<th class='sme-border'>Name</th>
@ -27,10 +32,10 @@
% my $control_data = $self->stash('ibays');
% foreach my $row (@$control_data) {
<tr>
<td class='sme-border'><%=$row->{Name}%></td>
<td class='sme-border'><%=$row->{Description}%></td>
<td class='sme-border'><%=$row->{flag}%></td>
<td class='sme-border'><%=$row->{PARAMS}%></td>
<td class='sme-border'><%=$c->render_to_string(inline=>$row->{Name})%></td>
<td class='sme-border'><%=$c->render_to_string(inline=>$row->{Description})%></td>
<td class='sme-border'><%=$c->render_to_string(inline=>$row->{flag})%></td>
<td class='sme-border'><%=$c->render_to_string(inline=>$row->{Modify})%></td>
</tr>
%}
</tbody>

View File

@ -1,22 +1,23 @@
'nfs_Delays the disk writing' => 'Delays the disk writing'
'nfs_Save' => 'Save'
'nfs_Set the uid and gid if you want all requests appear to be from one user or one group, otherwise leave blank' => 'Set the uid and gid if you want all requests appear to be from one user or one group, otherwise leave blank'
'nfs_NFS data share' => 'NFS data share'
'nfs_$thispanel successfull message' => '$thispanel successfull message'
'nfs Hello TABLE' => 'Hello TABLE'
'nfs_For writing permissions,allowing the root user and using insecure ports, you must configure a list of one IP per line, being part of the local network(s).' => 'For writing permissions,allowing the root user and using insecure ports, you must configure a list of one IP per line, being part of the local network(s).'
'nfs_Write (a)synchronously' => 'Write (a)synchronously'
'nfs_Share owner Group' => 'Share owner Group'
'nfs_File system permissions' => 'File system permissions'
'nfs_EnableShare on local network' => 'EnableShare on local network'
'nfs_Squash the power of users' => 'Squash the power of users'
'nfs_Set the GID.' => 'Set the GID.'
'nfs_These parameters will be effective only if the share is enabled. The share is in /home/e-smith/files/ibays//files' => 'These parameters will be effective only if the share is enabled. The share is in /home/e-smith/files/ibays//files'
'nfs_Enable the NFS Share' => 'Enable the NFS Share'
'nfs_APPLY' => 'APPLY'
'nfs_Requests on secure ports' => 'Requests on secure ports'
'nfs_APPLY' => 'APPLY'
'nfs_EnableShare on local network' => 'EnableShare on local network'
'nfs_Set the GID.' => 'Set the GID.'
'nfs_Save' => 'Save'
'nfs_Share owner Group' => 'Share owner Group'
'nfs_Browse the parent folders' => 'Browse the parent folders'
'nfs Hello TABLE' => 'Hello TABLE'
'nfs_File system permissions' => 'File system permissions'
'nfs_Delays the disk writing' => 'Delays the disk writing'
'nfs_NFS data share' => 'NFS data share'
'nfs_Set the UID.' => 'Set the UID.'
'nfs_NFS Client(s) allowed' => 'NFS Client(s) allowed'
'nfs_TABLE panel action was successfull' => 'TABLE panel action was successfull'
'nfs_For writing permissions,allowing the root user and using insecure ports, you must configure a list of one IP per line, being part of the local network(s).' => 'For writing permissions,allowing the root user and using insecure ports, you must configure a list of one IP per line, being part of the local network(s).'
'nfs_These parameters will be effective only if the share is enabled. The share is in /home/e-smith/files/ibays//files' => 'These parameters will be effective only if the share is enabled. The share is in /home/e-smith/files/ibays//files'
'nfs_Write (a)synchronously' => 'Write (a)synchronously'
'nfs_Squash the power of users' => 'Squash the power of users'
'nfs_Set the uid and gid if you want all requests appear to be from one user or one group, otherwise leave blank' => 'Set the uid and gid if you want all requests appear to be from one user or one group, otherwise leave blank'
'nfs_Enable the NFS Share' => 'Enable the NFS Share'
'nfs_PARAMS panel action was successfull' => 'PARAMS panel action was successfull'
'nfs Hello PARAMS' => 'Hello PARAMS'
'nfs_Information Bay name' => 'Information Bay name'
'nfs_Set the UID.' => 'Set the UID.'

View File

@ -1,6 +1,6 @@
package SrvMngr::Controller::${PackageName};
#
# Generated by SM2Gen version:${version}
# Generated by version:${version}
#
#----------------------------------------------------------------------
# heading : ${MenuHeading}
@ -8,44 +8,18 @@ package SrvMngr::Controller::${PackageName};
# navigation : ${MenuNavigation}
#
# name : ${lcPackageName}, method : get, url : /${lcPackageName}, ctlact : ${lcPackageName}#main
# name : ${lcPackageName}d, method : post, url : /${lcPackageName}d, ctlact : ${lcPackageName}#do_update
# name : ${lcPackageName}u, method : post, url : /${lcPackageName}u, ctlact : ${lcPackageName}#do_update
# name : ${lcPackageName}d, method : get, url : /${lcPackageName}d, ctlact : ${lcPackageName}#do_display
#
# routes : end
#
# Documentation: https://wiki.contribs.org/{PackageName}
# Documentation: https://wiki.contribs.org/${PackageName}
#----------------------------------------------------------------------
#
# Scheme of things:
#
#main:
##
## Initial entry
##
#set initial panel
#for initial panel:
# load up _data hash with DB fields
# load up stash with pointer(s) to control fields hash(= get-))
#render initial panel
#
#do_display
##
## Return after submit pushed on panel
##
#load up all params into local hash
# by panel:
# by param:
# validate param (return ret = ok or error message) - call validate-
# break out on error
#if validation not ok
# render back to current panel with error message in stash
#otherwise
# By panel:
# Copy back to DB any that have changed (how to easily tell if it has changed?)
# do whatever is required (inc signal_event smeserver-<whatever>-update?)
# set success
# call main?
# TBA!!
use strict;
use warnings;
@ -78,6 +52,16 @@ our $ddb = esmith::DomainsDB->open() || die("Couldn't open Domains db");
require '/usr/share/smanager/lib/SrvMngr/Controller/${PackageName}-Custom.pm'; #The code that is to be added by the developer
sub main {
#
# Initial entry - route is "/<whatever>"
#
#set initial panel
#for initial panel:
#Specifiy panel to enter
#load up _data hash with DB fields
#load up stash with pointer(s) to control fields hash(= get-))
#and a pointer to the prefix_data hash
#render initial panel
my $c = shift;
$c->app->log->info( $c->log_req );
@ -89,13 +73,14 @@ sub main {
$$${prefix}_data{'trt'} = '${firstPanel}';
#Load any DB entries into the <prefix>_data area so as they are preset in the form
# which DB
# which DB - this only really works if the initial panel is a PARAMS type panel and not a TABLE
my $db = $$${controldb | db | 'cdb'}; #pickup local or global db or Default to config
<tal:block tal:repeat="dbentry dbentries">$$${prefix}_data{${dbentry}} = $db->prop('${dbentry}') || ${dbdefault};
<tal:block tal:repeat="dbentry dbentries">
$$${prefix}_data{${dbentry}} = $db->prop('${dbentry}') || ${dbdefault | ""} || "";
</tal:block>
# and table control fields
<tal:block tal:repeat="tablecontrol tablecontrols"> $c->stash(${tablecontrol}=>get_${tablecontrol}());
<tal:block tal:repeat="tablecontrol tablecontrols"> $c->stash(${tablecontrol}=>get_${tablecontrol}($c));
</tal:block>
$c->stash(
@ -106,7 +91,32 @@ sub main {
$c->render( template => "${PackageName}" );
}
# Post request with params - submit from a form
sub do_update {
#
# Return after submit pushed on panel (this is a post) - route is "/<whatever>u"
# parameters in the params hash.
#
#load up all params into prefix_data hash:
#By panel (series of if statements - only one executed):
#call validate-PANEL() - return ret = ok or error message
#if validation not ok:
#render back to current panel with error message in stash
#otherwise:
#By panel (series of if statements - only one executed):
#do whatever is required: call perform-PANEL() - return "ok" or Error Message
#call signal-event for any global actions specified (check it exists - error and continue?)
#if action smeserver-<whatever>-update exists
#signal_event smeserver-<whatever>-update
#call signal-event for any specific actions for thids panel (check it exists first - error and continue)
#set success in stash
#if no "nextpanel" entry:
#set firstpanel
#else
#set nextpanel
#call render
my $c = shift;
$c->app->log->info($c->log_req);
@ -119,46 +129,114 @@ sub do_update {
# Get number of POST parameters
my $num_params = keys %params;
#Params are available in the hash "params"
# you may use:
my @result;
foreach my $key (keys %params) {
my $value = $params{$key};
push @result, { $key => $value };
$c->app->log->debug("$key: $value");
#Params are available in the hash "params" - copy to the prefix_data hash
while (my ($key, $value) = each %{$c->req->params->to_hash}) {
$$${prefix}_data{$key} = $value;
}
# the value of trt will tell you which panel has returned
my $trt = $c->param('trt') || '${firstPanel}' ; #hidden control on every form.
my $trt = $c->param('trt') || '${firstPanel}'; #hidden control on every form.
my $ret = 'ok';
#Validate the parameters accordingly
#Validate the parameters in a custom sub one for each panel (although only one of these will be executed)
my $thispanel;
<tal:block tal:repeat="panel panels">
if ($trt eq '${panel}'){
#Validate form parameters for panel ${panel}
$ret = validate_${panel}();
$ret = validate_${panel}(\%${prefix}_data);
$thispanel = '${panel}';
}
</tal:block>
if ($ret eq "ok") {
if ($ret ne "ok") {
# return to the panel with error message
$c->stash(error => $c->l($ret));
$c->render("${PackageName}");
} else {
#Do whatever is needed, including writing values to the DB
my $db = $$${controldb | db | 'cdb'}; #pickup local or global db or Default to config
<tal:block tal:repeat="dbentry dbentries">
$db->set_prop('${dbentry}'=> param{'${dbentry}'}; #Copy back into db
$$${prefix}_data{${dbentry}} = $db->prop('${dbentry}'); #Copy out into stash
<tal:block tal:repeat="panel panels">
if ($trt eq '${panel}'){
#do whatever is required ...
$ret = perform_${panel}(\%${prefix}_data);
if ($ret ne "ok") {
# return to the panel with error message
$c->stash(error => $c->l($ret));
$c->render("${PackageName}");
} else {
$c->stash( success => $c->l("${panel} panel action was successfull")); #A bit bland - edit it in the lex file
}
}
</tal:block>
# anything else here...
$c->stash( success => $c->l("$thispanel successfull message"));
# and call any signal-events needed
# Setup shared data and call panel
$c->stash(
title => $title,
${prefix}_data => \%${prefix}_data
# Extra data in here - repeat for each stash data entry needed for panels
);
${prefix}_data{'trt'} = '${firstPanel}';
if ('${nextpanel | "none"}' eq 'none') {
$$${prefix}_data{'trt'} = '${firstPanel}';
} else {
$$${prefix}_data{'trt'} = '${NextPanel | "none"}';
}
$c->render("${PackageName}");
}
}
sub do_display {
#
# Return after link clicked in table (this is a get) - route is "/<whatever>d"
# Expects ?trt=PANEL&selected="TableRowName" plus any other required
#
#load up all supplied params into prefix_data hash
#call get-selected-PANEL() - returns hash of all relevent parameters
#load up returned hash into prefix_data
#render - to called panel
my $c = shift;
$c->app->log->info($c->log_req);
my %${prefix}_data = ();
my $title = $c->l("${prefix}_${MenuDescription}");
# Accessing all POST parameters
my %params = $c->req->params->to_hash;
# Get number of POST parameters
my $num_params = keys %params;
#Params are available in the hash "params" - copy to the prefix_data hash
while (my ($key, $value) = each %{$c->req->params->to_hash}) {
$$${prefix}_data{$key} = $value;
}
# the value of trt will tell you which panel has returned
my $trt = $c->param('trt') || '${firstPanel}'; #Indicates where to go now
# Now add in the params from the selected row from the table
my %selectedrow;
<tal:block tal:repeat="panel panels">
if ($trt eq '${panel}'){
#Validate form parameters for panel ${panel}
%selectedrow = selected_${panel}($$${prefix}_data{'Selected'});
}
</tal:block>
#Copy in the selected row params to the prefix_data hash to pass to the panel
while (my ($key, $value) = each %selectedrow){
$$${prefix}_data{$key} = $value;
}
# Where to go now
$$${prefix}_data{'trt'} = $trt;
# Data for panel
$c->stash(
title => $title,
${prefix}_data => \%${prefix}_data
);
$c->render("${PackageName}");
}
1;

View File

@ -2,8 +2,7 @@
# Routines to be editted by the developer to provide validation for parameters
# and provison of the control data for table(s)
#
#
# Generated by SM2Gen version:${version}
# Generated by ${version}
#
use esmith::util;
@ -24,6 +23,7 @@ our $ddb = esmith::DomainsDB->open() || die("Couldn't open Domains db");
# Validation routines - parameters for each panel
<tal:block tal:repeat="panel panels">
sub validate_${panel} {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
@ -31,10 +31,31 @@ our $ddb = esmith::DomainsDB->open() || die("Couldn't open Domains db");
# Get control data for tables(s)
<tal:block tal:repeat="tablecontrol tablecontrols">
sub get_${tablecontrol} {
return []
}
sub get_${tablecontrol} {
my $c = shift;
@ret = {}
return \@ret
}
</tal:block>
# Return hash with values from row in which link clicked on table
<tal:block tal:repeat="panel panels">
sub validate_get_selected_${panel} {
$selected = shift; #Parameter is name of selected row.
%ret = {};
return $ret;
}
</tal:block>
#after sucessful modify or create or whatever and submit then perfom (if the params validate)
<tal:block tal:repeat="panel panels">
sub perform_${panel} {
$prefix_data = shift; #Data hash as parameter
$ret = 'ok';
return $ret;
}
</tal:block>
1;

View File

@ -43,7 +43,9 @@
<br></span></p>
]]></Textinput>
<SubHeader><![CDATA[<h2>${value}</h2>]]></SubHeader>
<SubHeader><![CDATA[
<h2>${value}</h2>]]>
</SubHeader>
<Paragraph><![CDATA[
<p>
@ -108,7 +110,7 @@
% my $control_data = $self->stash('${TableControl}');
% foreach my $row (@$control_data) {
<tr><tal:block tal:repeat="ColContent Columns">
<td class='sme-border'><%=$row->{${ColContent}}%></td></tal:block>
<td class='sme-border'><%=$c->render_to_string(inline=>$row->{${ColContent}})%></td></tal:block>
</tr>
%}
</tbody>

View File

@ -1,6 +1,6 @@
% layout 'default', title => "Sme server 2 - ${MenuDescription}", share_dir => './';
%#
%# Generated by SM2Gen version:${version}
%# Generated by ${version}
%#
% content_for 'module' => begin
<div id="module" class="module ${PackageName}-panel">

View File

@ -1,5 +1,5 @@
%#
%# Generated by SM2Gen version:${version}
%# Generated by ${version}
%#
<div id="${PackageName}-${route}">
<script>

View File

@ -0,0 +1,52 @@
* Scheme of things:
main:
#
# Initial entry - route is "/<whatever>"
#
set initial panel
for initial panel:
load up _data hash with DB fields
load up stash with pointer(s) to control fields hash(= get-))
and a pointer to the prefix_data hash
render initial panel
do_update:
#
# Return after submit pushed on panel (this is a post) - route is "/<whatever>u"
# parameters in the params hash.
#
load up all params into prefix_data hash:
By panel (series of if statements - only one executed):
call validate-PANEL() - return ret = ok or error message
if validation not ok:
render back to current panel with error message in stash
otherwise:
By panel (series of if statements - only one executed):
Copy back to DB all relevant params (is this just the DB params for this panel?)
do whatever is required: call perform-PANEL() - return "ok" or Error Message
call signal-event for any global actions specified (check it exists - error and continue?)
if action smeserver-<whatever>-update exists
signal_event smeserver-<whatever>-update
call signal-event for any specific actions for thids panel (check it exists first - error and continue)
set success in stash
if no "nextpanel" entry:
set firstpanel
else
set nextpanel
call render
do_display:
#
# Return after link clicked in table (this is a get) - route is "/<whatever>d"
# Expects ?trt=PANEL&selected="TableRowName" plus any other required
#
load up all supplied params into prefix_data hash
call get-selected-PANEL() - returns hash of all relevent parameters
load up returned hash into prefix_data
render - to called panel

View File

@ -5,6 +5,7 @@
MenuDescription: 'NFS data share',
MenuNavigation: '2000 400',
firstPanel: 'TABLE',
signalEvent: 'smeserver-nfsshare-update',
html: [
{
Name: 'params',
@ -138,7 +139,7 @@
Type:"Table",
TableControl:"ibays",
TopHeadings: ['Name','Description','Nfs status', 'Action'],
Columns: ['Name','Description','flag','PARAMS']
Columns: ['Name','Description','flag','Modify']
}
}
]

107
sm2gen.py
View File

@ -12,30 +12,9 @@ from datetime import datetime
import xml.etree.ElementTree as ET
SME2Gen_version = '0.6'
try:
chameleon_version = pkg_resources.get_distribution("Chameleon").version
except pkg_resources.DistributionNotFound:
chameleon_version = "Version information not available"
python_version = sys.version
python_version = python_version[:8]
current_datetime = datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M")
strVersion = "SME2Gen version:"+SME2Gen_version+" Chameleon version:"+chameleon_version+" On Python:"+python_version+" at "+formatted_datetime
json5_dict: dict = {}
json5_html_list: list = []
print(f"SM2 code from JSON5 - {strVersion}")
quit()
# Get the version of Chameleon using pkg_resources
try:
version = pkg_resources.get_distribution("Chameleon").version
print("Using Chameleon version:", version)
except pkg_resources.DistributionNotFound:
print("Chameleon is not installed or found.")
def parse_json(json_obj, prefix=''):
structured_list = []
if isinstance(json_obj, dict):
@ -203,29 +182,43 @@ def get_table_control_data():
return find_values_with_key(json5_html_list,'TableControl')
if __name__ == "__main__":
try:
chameleon_version = pkg_resources.get_distribution("Chameleon").version
except pkg_resources.DistributionNotFound:
chameleon_version = "Version information not available"
python_version = sys.version
python_version = python_version[:8]
current_datetime = datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M")
strVersion = "SME2Gen version:"+SME2Gen_version+" Chameleon version:"+chameleon_version+" On Python:"+python_version+" at "+formatted_datetime
json5_dict: dict = {}
json5_html_list: list = []
print(f"SM2 code from JSON5 - {strVersion}")
filename = '/home/brianr/clients/SM2/SM2Gen/nfsshare.json5'
# Command line parameters
parser = argparse.ArgumentParser(description="SM2Gen")
parser.add_argument('-f', '--filename', help='Specify a filename for the JSON5 file', default=filename)
parser.add_argument('-nc', '--noController', help='Stop it creating a controller file', default="no")
parser.add_argument('-nco', '--noController', help='Stop it creating a controller file', default="no")
parser.add_argument('-nh', '--noHtml', help='Stop it creating html files(s)', default="no")
parser.add_argument('-nl', '--noLang', help='Stop it creating language localise files(s)', default="no")
parser.add_argument('-ncu', '--noCust', help='Stop it creating Custom controller file', default="no")
args = parser.parse_args()
filename = args.filename
print(f"JSON5 from {filename} with noController={args.noController}, noHtml={args.noHtml} and noLang={args.noLang}") #Not yet activated
#print("Chameleon version:", chameleon.__version__)
# check syntax of JSON5
lint_json5(filename);
# Get dict of it all
json5_dict = json5_to_dict(filename)
#print(json5_dict)
# Get dict of just the html bit
json5_html_list = json5_dict['html']
#print(json5_html_list)
#Identify message
print(f"\nGenerating mojo panels for {hl('PackageName')}")
@ -238,9 +231,12 @@ if __name__ == "__main__":
#File names
controller_file = 'Targets/'+hl('PackageName')+'.pm'
custom_controller_file = 'Targets/'+hl('PackageName')+'-Custom.pm'
# see if it has been modified by developer
# see if it has been modified by developer - this did not work - the modified by was the same as the creation time/date
#if has_file_been_modified(custom_controller_file):
# custom_controller_file = custom_controller_file+'.new'
# Call it .new if one is already there (and may have been editted by the developer)
if os.path.exists(custom_controller_file):
custom_controller_file = custom_controller_file+'.new'
layout_file = 'Targets/'+hl('PackageName')+'.html.ep'
@ -250,19 +246,19 @@ if __name__ == "__main__":
print(partial_files)
lex_file = 'Targets/'+hl('PackageName').lower()+'_en.lex'
tablecontrols = get_table_control_data() #arrays of hashes used to drive rows in tables
#print(tablecontrols)
#quit()
#Generate controller file
try:
controller_template = PageTemplateFile("Templates/controller.pm.tem")
dbentries = get_db_fields() #Params which correspond to Db fields
try:
controller_perl = controller_template.render(tablecontrols=tablecontrols, dbentries=dbentries,**json5_dict,panels=routes,lcPackageName=json5_dict['PackageName'].lower())
#print()
#print(controller_perl)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#controller_perl = controller_perl.replace("$ ", "$")
controller_perl = controller_template.render(version=strVersion,
tablecontrols=tablecontrols,
dbentries=dbentries,
**json5_dict,
panels=routes,
lcPackageName=json5_dict['PackageName'].lower()
)
with open(controller_file, 'w') as file:
file.write(controller_perl)
print(f"{controller_file} controller generated ok")
@ -275,7 +271,10 @@ if __name__ == "__main__":
try:
custom_controller_template = PageTemplateFile("Templates/custom.pm.tem")
try:
custom_controller_perl = custom_controller_template.render(panels=routes,tablecontrols=tablecontrols)
custom_controller_perl = custom_controller_template.render(version=strVersion,
panels=routes,
tablecontrols=tablecontrols
)
# We must be careful to not overwrite the custom file if the developer has already written to it - TBD
with open(custom_controller_file, 'w') as file:
file.write(custom_controller_perl)
@ -289,16 +288,12 @@ if __name__ == "__main__":
layout_template = PageTemplateFile("Templates/layout.html.ep.tem")
try:
try:
layout_mojo = layout_template.render(**json5_dict,conditions=routes)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#layout_mojo = layout_mojo.replace("$ ", "$")
layout_mojo = layout_template.render(version=strVersion,**json5_dict,conditions=routes)
with open(layout_file, 'w') as file:
file.write(layout_mojo)
print(f"{layout_file} mojo template layout file generated ok")
except Exception as e:
print(f"An chameleon render on layout file error occurred: {e}")
#print()
#print(layout_mojo_template)
except Exception as e:
print(f"An chameleon template layout file error occurred: {e}")
@ -306,7 +301,6 @@ if __name__ == "__main__":
#Pull in the template code for each of the input types
#html_controls = json5_to_dict('Templates/html_controls.html.ep.tem')
html_controls = parse_xml_to_dict('Templates/html_controls.html.ep.xml')
#print(html_controls)
i = 0
for html in json5_html_list:
# Generate a mojo template file, and then add in the controls
@ -315,9 +309,7 @@ if __name__ == "__main__":
partial_template = PageTemplateFile("Templates/partial.html.ep.tem")
partial_mojo_context = {**json5_dict,**html}
try:
partial_mojo_template = partial_template.render(**partial_mojo_context)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#partial_mojo_template = partial_mojo_template.replace("$ ", "$")
partial_mojo_template = partial_template.render(version=strVersion,**partial_mojo_context)
with open( partial_files[i], 'w') as file:
file.write(partial_mojo_template)
print(f"{partial_files[i]} mojo template generated ok - phase 1")
@ -327,31 +319,15 @@ if __name__ == "__main__":
print(f"An chameleon html {html['route']} error occurred: {e}")
#Now generate the controls from the rest of the entries in the dict.
#print()
#print(html['route']);
all_controls_html = "";
prefix_is = hl('prefix')
for html_control in html:
#print(html_control)
inner_html = html[html_control]
if isinstance(inner_html, dict):
#print("\t\t"+inner_html['route']+":"+inner_html['Type'])
try:
control_template = PageTemplate(html_controls[inner_html['Type']])
try:
control_html = control_template.render(**inner_html,prefix=prefix_is) #Contents=Contents,Headings=Headings)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#control_html = control_html.replace("$ ", "$")
# Add in two tabs before each newline
#control_html = control_html.replace("\n", "\n\t\t")
# and an extra tab before each "%"
#control_html = control_html.replace("%", "\t%")
#print(control_html)
# And re-run it if the type is "table"
#if inner_html['Type'] == 'Table'
#Another scan
# print("Another scan for the table")
#Else just move on.
control_html = control_template.render(version=strVersion,**inner_html,prefix=prefix_is)
all_controls_html = all_controls_html + control_html
except Exception as e:
print(f"An chameleon render on partial file control {inner_html['Name']} error occurred: {e}")
@ -360,15 +336,10 @@ if __name__ == "__main__":
else:
#just a simple entry - name less numerics is type
html_Type = ''.join(char for char in html_control if not char.isdigit())
#print(html_Type);
try:
simple_control_template = PageTemplate(html_controls[html_Type])
try:
simple_control_html = simple_control_template.render(value=inner_html,prefix=prefix_is)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#simple_control_html = simple_control_html.replace("$ ", "$")
# Add in two tabs before each newline
#simple_control_html = simple_control_html.replace("\n", "\n\t\t")
simple_control_html = simple_control_template.render(version=strVersion,value=inner_html,prefix=prefix_is)
all_controls_html = all_controls_html + simple_control_html
except Exception as e:
print(f"An chameleon render on partial file control {html_control} error occurred: {e}")
@ -395,7 +366,6 @@ if __name__ == "__main__":
# create a combined list of all the files
all_files = [controller_file,layout_file]+partial_files
#print(all_files)
all_strings = []
for filename in all_files:
with open(filename, 'r') as file:
@ -404,12 +374,9 @@ if __name__ == "__main__":
pattern = r"l[\s|(][\'|\"](.*)[\'|\"]\)"
# Use re.findall to extract all occurrences of the pattern from the file content
extracted_strings = re.findall(pattern, file_content)
#print(len(extracted_strings))
all_strings = all_strings + extracted_strings
#print(len(all_strings))
#Take out any duplicates
all_strings = deduplicate_array(all_strings)
#print(len(all_strings))
# Now process them one by one into the lexical file
lex_all = "";
# '<prefix>_english-message' => 'English Message',