Compare commits

..
11 Commits
Author SHA1 Message Date
pvincent ef31c26525 tagged as 1.8.2 2021-08-27 17:41:56 +04:00
pvincent ed931b7b2c App.sendMail 2021-08-27 17:41:44 +04:00
pvincent 089f137636 tagged as 1.8.1 2021-08-26 17:11:58 +04:00
pvincent 0426a175aa App.log 2021-08-26 17:11:16 +04:00
pvincent 59b7c48a89 tagged as 1.8.0 2021-08-25 22:23:45 +04:00
pvincent d13c85be61 force semver 2021-08-25 22:23:28 +04:00
pvincent 2714f44b44 README 2021-08-25 22:21:59 +04:00
pvincent 04cb4343ad semver 2021-08-25 22:20:29 +04:00
pvincent e94c4eae67 App.log for DEBUG 2021-08-25 22:17:03 +04:00
pvincent 47abd95962 tagged as 1.7.3 2021-08-25 19:23:35 +04:00
pvincent c346584d46 change readme 2021-08-25 19:23:20 +04:00
9 changed files with 1054 additions and 1013 deletions
+2 -1
View File
@@ -30,8 +30,9 @@ www/file/*
www/js/app.js www/js/app.js
www/js/libs.js www/js/libs.js
www/css/.sass-cache www/css/.sass-cache
www/css/*.css www/css/*.css
!www/css/bootstrap.min.css !www/css/bootstrap.min.css
config-dev.xml
config-prod.xml
+1 -1
View File
@@ -1 +1 @@
1.7.2 1.8.2
+1
View File
@@ -74,6 +74,7 @@ templates:
@make LANG=fr ctemplates @make LANG=fr ctemplates
msgfmt www/lang/texts_fr.po -o www/lang/texts_fr.mo msgfmt www/lang/texts_fr.po -o www/lang/texts_fr.mo
chown www-data:www-data -R www chown www-data:www-data -R www
chown www-data:www-data -R lang
ctemplates: ctemplates:
(cd lang/$(LANG)/tpl; temploc2 -macros macros.mtt -output ../tmp/ *.mtt */*.mtt */*/*.mtt) (cd lang/$(LANG)/tpl; temploc2 -macros macros.mtt -output ../tmp/ *.mtt */*.mtt */*/*.mtt)
+3 -1
View File
@@ -9,7 +9,7 @@ j'ai repris sur la base d'un existant pour adapter au marché local réunionnais
## INSTALL FROM SCRATCH (debian-buster) ## INSTALL FROM SCRATCH (debian-buster)
* apt install -y curl * apt install -y curl
* curl -sL https://deb.nodesource.com/setup_8.x | bash - * curl -L https://deb.nodesource.com/setup_8.x | bash -
* apt install -y nodejs=8.17.0-1nodesource1 * apt install -y nodejs=8.17.0-1nodesource1
* apt install -y sudo haxe apache2 make git imagemagick gettext libapache2-mod-neko mariadb-server * apt install -y sudo haxe apache2 make git imagemagick gettext libapache2-mod-neko mariadb-server
* mysql -u root <<EOF * mysql -u root <<EOF
@@ -28,6 +28,8 @@ EOF
ServerName cagettepei ServerName cagettepei
DirectoryIndex index.n DirectoryIndex index.n
DocumentRoot /var/www/cagettepei/www/ DocumentRoot /var/www/cagettepei/www/
</VirtualHost> </VirtualHost>
``` ```
* sed -i '/<Directory \/var\/www\/>/,/<\/Directory>/ s/AllowOverride None/AllowOverride All/' /etc/apache2/apache2.conf * sed -i '/<Directory \/var\/www\/>/,/<\/Directory>/ s/AllowOverride None/AllowOverride All/' /etc/apache2/apache2.conf
+1 -1
View File
@@ -47,5 +47,5 @@
"bugs": { "bugs": {
"url": "https://github.com/bablukid/cagette/issues" "url": "https://github.com/bablukid/cagette/issues"
}, },
"version": "1.7.2" "version": "1.8.2"
} }
+22 -26
View File
@@ -3,7 +3,6 @@ import thx.semver.Version;
import Common; import Common;
class App extends sugoi.BaseApp { class App extends sugoi.BaseApp {
public static var current:App = null; public static var current:App = null;
public static var t:sugoi.i18n.translator.ITranslator; public static var t:sugoi.i18n.translator.ITranslator;
public static var config = sugoi.BaseApp.config; public static var config = sugoi.BaseApp.config;
@@ -24,7 +23,6 @@ class App extends sugoi.BaseApp {
} }
public static function main() { public static function main() {
App.t = sugoi.form.Form.translator = new sugoi.i18n.translator.TMap(getTranslationArray(), "fr"); App.t = sugoi.form.Form.translator = new sugoi.i18n.translator.TMap(getTranslationArray(), "fr");
sugoi.BaseApp.main(); sugoi.BaseApp.main();
} }
@@ -51,8 +49,10 @@ class App extends sugoi.BaseApp {
} }
public function getCurrentGroup() { public function getCurrentGroup() {
if (session == null) return null; if (session == null)
if (session.data == null ) return null; return null;
if (session.data == null)
return null;
var a = session.data.amapId; var a = session.data.amapId;
if (a == null) { if (a == null) {
return null; return null;
@@ -62,7 +62,6 @@ class App extends sugoi.BaseApp {
} }
override function beforeDispatch() { override function beforeDispatch() {
// send "current page" event // send "current page" event
event(Page(this.uri)); event(Page(this.uri));
@@ -71,22 +70,22 @@ class App extends sugoi.BaseApp {
public function getPlugin(name:String):sugoi.plugin.IPlugIn { public function getPlugin(name:String):sugoi.plugin.IPlugIn {
for (p in plugins) { for (p in plugins) {
if (p.getName() == name) return p; if (p.getName() == name)
return p;
} }
return null; return null;
} }
public static function log(t:Dynamic) { public static function log(t:Dynamic, ?infos:haxe.PosInfos) {
if(App.config.DEBUG) { // if (App.config.DEBUG) {
neko.Web.logMessage(Std.string(t)); //write in Apache error log // neko.Web.logMessage(Std.string(t)); // write in Apache error log
#if weblog // }
Weblog.log(t); //write en Weblog console (https://lib.haxe.org/p/weblog/) neko.Web.logMessage('[${infos.fileName}:${infos.lineNumber} ${infos.className}#${infos.methodName}] ' + Std.string(t));
#end
}
} }
public function event(e:Event) { public function event(e:Event) {
if(e==null) return null; if (e == null)
return null;
this.eventDispatcher.dispatch(e); this.eventDispatcher.dispatch(e);
return e; return e;
} }
@@ -231,15 +230,12 @@ class App extends sugoi.BaseApp {
} }
public static function getMailer():sugoi.mail.IMailer { public static function getMailer():sugoi.mail.IMailer {
var mailer:sugoi.mail.IMailer = new sugoi.mail.BufferedMailer(); var mailer:sugoi.mail.IMailer = new sugoi.mail.BufferedMailer();
if (App.config.DEBUG) { if (App.config.DEBUG) {
App.log("DEBUGEmailer enabled => emails are written to tmp folder");
//Dev env : emails are written to tmp folder
mailer = new sugoi.mail.DebugMailer(); mailer = new sugoi.mail.DebugMailer();
} else { } else {
if (sugoi.db.Variable.get("mailer") == null) { if (sugoi.db.Variable.get("mailer") == null) {
var msg = sugoi.i18n.Locale.texts._("Please configure the email settings in a <href='/admin/emails'>this section</a>"); var msg = sugoi.i18n.Locale.texts._("Please configure the email settings in a <href='/admin/emails'>this section</a>");
throw sugoi.ControllerAction.ErrorAction("/", msg); throw sugoi.ControllerAction.ErrorAction("/", msg);
@@ -260,18 +256,21 @@ class App extends sugoi.BaseApp {
* Send an email * Send an email
*/ */
public static function sendMail(m:sugoi.mail.Mail, ?group:db.Amap, ?listId:String, ?sender:db.User) { public static function sendMail(m:sugoi.mail.Mail, ?group:db.Amap, ?listId:String, ?sender:db.User) {
if (group == null)
if (group == null) group = App.current.user == null ? null:App.current.user.getAmap(); group = App.current.user == null ? null : App.current.user.getAmap();
current.event(SendEmail(m)); current.event(SendEmail(m));
var params = group == null ? null : {remoteId: group.id}; var params = group == null ? null : {remoteId: group.id};
App.log('about to send email with subject=<${m.getSubject()}> ...');
getMailer().send(m, params, function(o) {}); getMailer().send(m, params, function(o) {});
App.log('email from=<${m.getSender().email}>, subject=<${m.getSubject()}> successfully sent');
} }
public static function quickMail(to:String, subject:String, html:String, ?group:db.Amap) { public static function quickMail(to:String, subject:String, html:String, ?group:db.Amap) {
App.log('quickMail subject=$subject');
var e = new sugoi.mail.Mail(); var e = new sugoi.mail.Mail();
e.setSubject(subject); e.setSubject(subject);
e.setRecipient(to); e.setRecipient(to);
@@ -287,7 +286,6 @@ class App extends sugoi.BaseApp {
* @param ctx * @param ctx
*/ */
public function processTemplate(tpl:String, ctx:Dynamic):String { public function processTemplate(tpl:String, ctx:Dynamic):String {
Reflect.setField(ctx, 'HOST', App.config.HOST); Reflect.setField(ctx, 'HOST', App.config.HOST);
Reflect.setField(ctx, 'hDate', App.current.view.hDate); Reflect.setField(ctx, 'hDate', App.current.view.hDate);
// i18n functions // i18n functions
@@ -297,11 +295,9 @@ class App extends sugoi.BaseApp {
var tpl = loadTemplate(tpl); var tpl = loadTemplate(tpl);
var html = tpl.execute(ctx); var html = tpl.execute(ctx);
#if php #if php
if ( html.substr(0, 4) == "null") html = html.substr(4); if (html.substr(0, 4) == "null")
html = html.substr(4);
#end #end
return html; return html;
} }
} }
+133 -127
View File
@@ -1,4 +1,5 @@
package controller; package controller;
import db.UserContract; import db.UserContract;
import sugoi.form.elements.Checkbox; import sugoi.form.elements.Checkbox;
import sugoi.form.elements.Selectbox; import sugoi.form.elements.Selectbox;
@@ -6,19 +7,20 @@ import sugoi.form.Form;
import sugoi.form.elements.StringInput; import sugoi.form.elements.StringInput;
import Common; import Common;
import datetime.DateTime; import datetime.DateTime;
using tools.ObjectListTool; using tools.ObjectListTool;
using tools.DateTool; using tools.DateTool;
import service.OrderService; import service.OrderService;
class ContractAdmin extends Controller class ContractAdmin extends Controller {
{ public function new() {
public function new()
{
super(); super();
if (!app.user.isContractManager()) throw Error("/", t._("You don't have the authorization to manage contracts")); if (!app.user.isContractManager())
throw Error("/", t._("You don't have the authorization to manage contracts"));
view.nav = ["contractadmin"]; view.nav = ["contractadmin"];
App.log("first message");
} }
public function sendNav(c) { public function sendNav(c) {
@@ -33,7 +35,6 @@ class ContractAdmin extends Controller
*/ */
@tpl("contractadmin/default.mtt") @tpl("contractadmin/default.mtt")
function doDefault(?args:{old:Bool}) { function doDefault(?args:{old:Bool}) {
view.nav.push("default"); view.nav.push("default");
var now = Date.now(); var now = Date.now();
@@ -48,7 +49,8 @@ class ContractAdmin extends Controller
// filter if current user is not manager // filter if current user is not manager
if (!app.user.isAmapManager()) { if (!app.user.isAmapManager()) {
for (c in Lambda.array(contracts).copy()) { for (c in Lambda.array(contracts).copy()) {
if(!app.user.canManageContract(c)) contracts.remove(c); if (!app.user.canManageContract(c))
contracts.remove(c);
} }
} }
@@ -65,7 +67,6 @@ class ContractAdmin extends Controller
if(md.hasOnlyConstantOrders()) multidistribs.remove(md); if(md.hasOnlyConstantOrders()) multidistribs.remove(md);
}*/ }*/
view.multidistribs = multidistribs; view.multidistribs = multidistribs;
} else { } else {
view.multidistribs = []; view.multidistribs = [];
} }
@@ -79,14 +80,18 @@ class ContractAdmin extends Controller
view.nav.push("products"); view.nav.push("products");
sendNav(contract); sendNav(contract);
if (!app.user.canManageContract(contract)) throw Error("/", t._("Access forbidden") ); if (!app.user.canManageContract(contract))
throw Error("/", t._("Access forbidden"));
view.c = contract; view.c = contract;
// checks // checks
if (app.user.amap.hasShopMode() && !app.user.amap.hasTaxonomy()) { if (app.user.amap.hasShopMode() && !app.user.amap.hasTaxonomy()) {
for (p in contract.getProducts(false)) { for (p in contract.getProducts(false)) {
if (p.getCategories().length == 0) { if (p.getCategories().length == 0) {
app.session.addMessage(t._("Warning, at least one product does not have any category. <a href='/product/categorize/::contractid::'>Click here to add categories</a>", {contractid:contract.id}), true); app.session.addMessage(t._("Warning, at least one product does not have any category. <a href='/product/categorize/::contractid::'>Click here to add categories</a>",
{
contractid: contract.id
}), true);
break; break;
} }
} }
@@ -94,7 +99,6 @@ class ContractAdmin extends Controller
// batch enable / disable products // batch enable / disable products
if (args != null) { if (args != null) {
if (args.disable != null) { if (args.disable != null) {
var pids = Lambda.array(Lambda.map(args.disable.split("|"), function(x) return Std.parseInt(x))); var pids = Lambda.array(Lambda.map(args.disable.split("|"), function(x) return Std.parseInt(x)));
service.ProductService.batchDisableProducts(pids); service.ProductService.batchDisableProducts(pids);
@@ -104,14 +108,12 @@ class ContractAdmin extends Controller
var pids = Lambda.array(Lambda.map(args.enable.split("|"), function(x) return Std.parseInt(x))); var pids = Lambda.array(Lambda.map(args.enable.split("|"), function(x) return Std.parseInt(x)));
service.ProductService.batchEnableProducts(pids); service.ProductService.batchEnableProducts(pids);
} }
} }
// generate a token // generate a token
checkToken(); checkToken();
} }
/** /**
* - hidden page - * - hidden page -
* copy products from a contract to an other * copy products from a contract to an other
@@ -125,7 +127,6 @@ class ContractAdmin extends Controller
form.addElement(new sugoi.form.elements.Selectbox("source", t._("Copy products from: "), Lambda.array(contracts))); form.addElement(new sugoi.form.elements.Selectbox("source", t._("Copy products from: "), Lambda.array(contracts)));
form.addElement(new sugoi.form.elements.Checkbox("delete", t._("Delete existing products (all orders will be deleted!)"))); form.addElement(new sugoi.form.elements.Checkbox("delete", t._("Delete existing products (all orders will be deleted!)")));
if (form.checkToken()) { if (form.checkToken()) {
if (form.getValueOf("delete") == "1") { if (form.getValueOf("delete") == "1") {
for (p in contract.getProducts()) { for (p in contract.getProducts()) {
p.lock(); p.lock();
@@ -145,11 +146,8 @@ class ContractAdmin extends Controller
} }
throw Ok("/contractAdmin/products/" + contract.id, t._("Products copied from ") + source.name); throw Ok("/contractAdmin/products/" + contract.id, t._("Products copied from ") + source.name);
} }
view.form = form; view.form = form;
} }
@@ -159,7 +157,6 @@ class ContractAdmin extends Controller
*/ */
@tpl('contractadmin/calendar.mtt') @tpl('contractadmin/calendar.mtt')
public function doCalendar() { public function doCalendar() {
var contracts = db.Contract.getActiveContracts(app.user.amap, true, false); var contracts = db.Contract.getActiveContracts(app.user.amap, true, false);
// Events of the month in a calendar // Events of the month in a calendar
@@ -203,18 +200,13 @@ class ContractAdmin extends Controller
v.push({name: t._("End of orders") + d.contract.name, color: Calendar.COLOR_ORDER}); v.push({name: t._("End of orders") + d.contract.name, color: Calendar.COLOR_ORDER});
cal.set(k, v); cal.set(k, v);
} }
} }
} }
} }
var n = Date.now(); var n = Date.now();
view.now = new Date(n.getFullYear(), n.getMonth(), n.getDate(), 0, 0, 0).getTime(); view.now = new Date(n.getFullYear(), n.getMonth(), n.getDate(), 0, 0, 0).getTime();
view.calendar = Calendar.mapToArray(cal); view.calendar = Calendar.mapToArray(cal);
} }
/** /**
@@ -222,16 +214,13 @@ class ContractAdmin extends Controller
*/ */
@tpl('contractadmin/ordersByTimeFrame.mtt') @tpl('contractadmin/ordersByTimeFrame.mtt')
function doOrdersByTimeFrame(?from:Date, ?to:Date /*, ?place:db.Place*/) { function doOrdersByTimeFrame(?from:Date, ?to:Date /*, ?place:db.Place*/) {
if (from == null) { if (from == null) {
var f = new sugoi.form.Form("listBydate", null, sugoi.form.Form.FormMethod.GET); var f = new sugoi.form.Form("listBydate", null, sugoi.form.Form.FormMethod.GET);
var now = DateTime.now(); var now = DateTime.now();
var from = now.snap(Month(Down)).getDate(); var from = now.snap(Month(Down)).getDate();
var to = now.snap(Month(Up)).add(Day(-1)).getDate(); var to = now.snap(Month(Up)).add(Day(-1)).getDate();
var el = new sugoi.form.elements.DatePicker("from", t._("Start date"), from, true); var el = new sugoi.form.elements.DatePicker("from", t._("Start date"), from, true);
el.format = 'LL'; el.format = 'LL';
f.addElement(el); f.addElement(el);
@@ -248,32 +237,33 @@ class ContractAdmin extends Controller
app.setTemplate("form.mtt"); app.setTemplate("form.mtt");
if (f.checkToken()) { if (f.checkToken()) {
var url = '/contractAdmin/ordersByTimeFrame/' + f.getValueOf("from").toString().substr(0, 10) + "/"
var url = '/contractAdmin/ordersByTimeFrame/' + f.getValueOf("from").toString().substr(0, 10) +"/"+f.getValueOf("to").toString().substr(0, 10); + f.getValueOf("to").toString().substr(0, 10);
// var p = f.getValueOf("placeId"); // var p = f.getValueOf("placeId");
// if (p != null) url += "/"+p; // if (p != null) url += "/"+p;
throw Redirect(url); throw Redirect(url);
} }
return; return;
} else { } else {
var d1 = tools.DateTool.setHourMinute(from, 0, 0); var d1 = tools.DateTool.setHourMinute(from, 0, 0);
var d2 = tools.DateTool.setHourMinute(to, 23, 59); var d2 = tools.DateTool.setHourMinute(to, 23, 59);
var contracts = app.user.amap.getActiveContracts(true); var contracts = app.user.amap.getActiveContracts(true);
var cconst = []; var cconst = [];
var cvar = []; var cvar = [];
for (c in contracts) { for (c in contracts) {
if (c.type == db.Contract.TYPE_CONSTORDERS) cconst.push(c.id); if (c.type == db.Contract.TYPE_CONSTORDERS)
if (c.type == db.Contract.TYPE_VARORDER) cvar.push(c.id); cconst.push(c.id);
if (c.type == db.Contract.TYPE_VARORDER)
cvar.push(c.id);
} }
// distribs // distribs
var vdistribs = db.Distribution.manager.search(($contractId in cvar) && $date >= d1 && $date <= d2 /*&& place.id==$placeId*/, false); var vdistribs = db.Distribution.manager.search(($contractId in cvar) && $date >= d1 && $date <= d2 /*&& place.id==$placeId*/, false);
var cdistribs = db.Distribution.manager.search(($contractId in cconst) && $date >= d1 && $date <= d2 /*&& place.id==$placeId*/, false); var cdistribs = db.Distribution.manager.search(($contractId in cconst) && $date >= d1 && $date <= d2 /*&& place.id==$placeId*/, false);
if (vdistribs.length == 0 && cdistribs.length == 0) throw Error("/contractAdmin/ordersByDate", t._("There is no delivery at this date")); if (vdistribs.length == 0 && cdistribs.length == 0)
throw Error("/contractAdmin/ordersByDate", t._("There is no delivery at this date"));
// varying orders // varying orders
var varorders = db.UserContract.manager.search($distributionId in vdistribs.getIds(), {orderBy: userId}); var varorders = db.UserContract.manager.search($distributionId in vdistribs.getIds(), {orderBy: userId});
@@ -293,11 +283,7 @@ class ContractAdmin extends Controller
view.from = from; view.from = from;
view.to = to; view.to = to;
view.ctotal = app.params.exists("ctotal"); view.ctotal = app.params.exists("ctotal");
} }
} }
/** /**
@@ -308,7 +294,6 @@ class ContractAdmin extends Controller
@tpl('contractadmin/ordersByDate.mtt') @tpl('contractadmin/ordersByDate.mtt')
function doOrdersByDate(?date:Date, ?place:db.Place) { function doOrdersByDate(?date:Date, ?place:db.Place) {
if (date == null) { if (date == null) {
var f = new sugoi.form.Form("listBydate", null, sugoi.form.Form.FormMethod.GET); var f = new sugoi.form.Form("listBydate", null, sugoi.form.Form.FormMethod.GET);
var el = new sugoi.form.elements.DatePicker("date", t._("Delivery date"), true); var el = new sugoi.form.elements.DatePicker("date", t._("Delivery date"), true);
el.format = 'LL'; el.format = 'LL';
@@ -324,32 +309,33 @@ class ContractAdmin extends Controller
app.setTemplate("form.mtt"); app.setTemplate("form.mtt");
if (f.checkToken()) { if (f.checkToken()) {
var url = '/contractAdmin/ordersByDate/' + f.getValueOf("date").toString().substr(0, 10); var url = '/contractAdmin/ordersByDate/' + f.getValueOf("date").toString().substr(0, 10);
var p = f.getValueOf("placeId"); var p = f.getValueOf("placeId");
if (p != null) url += "/"+p; if (p != null)
url += "/" + p;
throw Redirect(url); throw Redirect(url);
} }
return; return;
} else { } else {
var d1 = date.setHourMinute(0, 0); var d1 = date.setHourMinute(0, 0);
var d2 = date.setHourMinute(23, 59); var d2 = date.setHourMinute(23, 59);
var contracts = app.user.amap.getActiveContracts(true); var contracts = app.user.amap.getActiveContracts(true);
var cconst = []; var cconst = [];
var cvar = []; var cvar = [];
for (c in contracts) { for (c in contracts) {
if (c.type == db.Contract.TYPE_CONSTORDERS) cconst.push(c.id); if (c.type == db.Contract.TYPE_CONSTORDERS)
if (c.type == db.Contract.TYPE_VARORDER) cvar.push(c.id); cconst.push(c.id);
if (c.type == db.Contract.TYPE_VARORDER)
cvar.push(c.id);
} }
// distribs // distribs
var vdistribs = db.Distribution.manager.search(($contractId in cvar) && $date >= d1 && $date <= d2 && place.id == $placeId, false); var vdistribs = db.Distribution.manager.search(($contractId in cvar) && $date >= d1 && $date <= d2 && place.id == $placeId, false);
var cdistribs = db.Distribution.manager.search(($contractId in cconst) && $date >= d1 && $date <= d2 && place.id == $placeId, false); var cdistribs = db.Distribution.manager.search(($contractId in cconst) && $date >= d1 && $date <= d2 && place.id == $placeId, false);
if (vdistribs.length == 0 && cdistribs.length == 0) throw Error("/contractAdmin/ordersByDate", t._("There is no delivery at this date")); if (vdistribs.length == 0 && cdistribs.length == 0)
throw Error("/contractAdmin/ordersByDate", t._("There is no delivery at this date"));
// varying orders // varying orders
var varorders = db.UserContract.manager.search($distributionId in vdistribs.getIds(), {orderBy: userId}); var varorders = db.UserContract.manager.search($distributionId in vdistribs.getIds(), {orderBy: userId});
@@ -372,13 +358,11 @@ class ContractAdmin extends Controller
} }
} }
/** /**
* Global view on orders, producer view * Global view on orders, producer view
*/ */
@tpl('contractadmin/vendorsByDate.mtt') @tpl('contractadmin/vendorsByDate.mtt')
function doVendorsByDate(date:Date, place:db.Place) { function doVendorsByDate(date:Date, place:db.Place) {
var d1 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var d1 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var d2 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59); var d2 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
var contracts = app.user.amap.getActiveContracts(true); var contracts = app.user.amap.getActiveContracts(true);
@@ -387,8 +371,8 @@ class ContractAdmin extends Controller
// distribs for both types in active contracts // distribs for both types in active contracts
var distribs = db.Distribution.manager.search(($contractId in cids) && $date >= d1 && $date <= d2 && $place == place, false); var distribs = db.Distribution.manager.search(($contractId in cids) && $date >= d1 && $date <= d2 && $place == place, false);
if (distribs.length == 0)
if ( distribs.length == 0 ) throw Error("/contractAdmin/ordersByDate", t._("There is no delivery at this date")); throw Error("/contractAdmin/ordersByDate", t._("There is no delivery at this date"));
var out = new Map<Int, Dynamic>(); // key : vendor id var out = new Map<Int, Dynamic>(); // key : vendor id
@@ -399,10 +383,8 @@ class ContractAdmin extends Controller
if (o == null) { if (o == null) {
out.set(vid, {contract: d.contract, distrib: d, orders: service.ReportService.getOrdersByProduct(d)}); out.set(vid, {contract: d.contract, distrib: d, orders: service.ReportService.getOrdersByProduct(d)});
} else { } else {
// add orders with existing ones // add orders with existing ones
for (x in service.ReportService.getOrdersByProduct(d)) { for (x in service.ReportService.getOrdersByProduct(d)) {
// find record in existing orders // find record in existing orders
var f:Dynamic = Lambda.find(o.orders, function(a) return a.pid == x.pid); var f:Dynamic = Lambda.find(o.orders, function(a) return a.pid == x.pid);
if (f == null) { if (f == null) {
@@ -422,13 +404,11 @@ class ContractAdmin extends Controller
view.date = date; view.date = date;
} }
/** /**
* Global view on orders, producer view * Global view on orders, producer view
*/ */
@tpl('contractadmin/vendorsByTimeFrame.mtt') @tpl('contractadmin/vendorsByTimeFrame.mtt')
function doVendorsByTimeFrame(from:Date, to:Date) { function doVendorsByTimeFrame(from:Date, to:Date) {
var d1 = tools.DateTool.setHourMinute(from, 0, 0); var d1 = tools.DateTool.setHourMinute(from, 0, 0);
var d2 = tools.DateTool.setHourMinute(to, 23, 59); var d2 = tools.DateTool.setHourMinute(to, 23, 59);
var contracts = app.user.amap.getActiveContracts(true); var contracts = app.user.amap.getActiveContracts(true);
@@ -436,7 +416,8 @@ class ContractAdmin extends Controller
// distribs for both types in active contracts // distribs for both types in active contracts
var distribs = db.Distribution.manager.search(($contractId in cids) && $date >= d1 && $date <= d2 /*&& $place==place*/, false); var distribs = db.Distribution.manager.search(($contractId in cids) && $date >= d1 && $date <= d2 /*&& $place==place*/, false);
if ( distribs.length == 0 ) throw Error("/contractAdmin/", t._("There is no delivery during this period")); if (distribs.length == 0)
throw Error("/contractAdmin/", t._("There is no delivery during this period"));
var out = new Map<Int, {contract:db.Contract, distrib:db.Distribution, orders:Array<OrderByProduct>}>(); // key : vendor id var out = new Map<Int, {contract:db.Contract, distrib:db.Distribution, orders:Array<OrderByProduct>}>(); // key : vendor id
@@ -447,10 +428,8 @@ class ContractAdmin extends Controller
if (o == null) { if (o == null) {
out.set(vid, {contract: d.contract, distrib: d, orders: service.ReportService.getOrdersByProduct(d)}); out.set(vid, {contract: d.contract, distrib: d, orders: service.ReportService.getOrdersByProduct(d)});
} else { } else {
// add orders with existing ones // add orders with existing ones
for (x in service.ReportService.getOrdersByProduct(d)) { for (x in service.ReportService.getOrdersByProduct(d)) {
// find record in existing orders // find record in existing orders
var f:OrderByProduct = Lambda.find(o.orders, function(a:OrderByProduct) return a.pid == x.pid); var f:OrderByProduct = Lambda.find(o.orders, function(a:OrderByProduct) return a.pid == x.pid);
if (f == null) { if (f == null) {
@@ -476,11 +455,28 @@ class ContractAdmin extends Controller
var orders = []; var orders = [];
for (x in out) { for (x in out) {
// empty line // empty line
orders.push({"quantity":null, "pname":null, "ref":null, "priceHT":null, "priceTTC":null, "totalHT":null, "totalTTC":null}); orders.push({
orders.push({"quantity":null, "pname":x.contract.vendor.name, "ref":null, "priceHT":null, "priceTTC":null, "totalHT":null, "totalTTC":null}); "quantity": null,
"pname": null,
"ref": null,
"priceHT": null,
"priceTTC": null,
"totalHT": null,
"totalTTC": null
});
orders.push({
"quantity": null,
"pname": x.contract.vendor.name,
"ref": null,
"priceHT": null,
"priceTTC": null,
"totalHT": null,
"totalTTC": null
});
for (o in x.orders) { for (o in x.orders) {
if(o.vat==null) o.vat = 0; if (o.vat == null)
o.vat = 0;
orders.push({ orders.push({
"quantity": view.formatNum(o.quantity), "quantity": view.formatNum(o.quantity),
"pname": o.pname, "pname": o.pname,
@@ -506,9 +502,9 @@ class ContractAdmin extends Controller
}); });
totalTTC = 0; totalTTC = 0;
totalHT = 0; totalHT = 0;
} }
var fileName = t._("Orders from the ::fromDate:: to the ::toDate:: per supplier.csv", {fromDate:from.toString().substr(0, 10), toDate:to.toString().substr(0, 10)}); var fileName = t._("Orders from the ::fromDate:: to the ::toDate:: per supplier.csv",
{fromDate: from.toString().substr(0, 10), toDate: to.toString().substr(0, 10)});
sugoi.tools.Csv.printCsvDataFromObjects(orders, ["quantity", "pname", "ref", "priceHT", "priceTTC", "totalHT", "totalTTC"], fileName); sugoi.tools.Csv.printCsvDataFromObjects(orders, ["quantity", "pname", "ref", "priceHT", "priceTTC", "totalHT", "totalTTC"], fileName);
return; return;
} }
@@ -517,7 +513,6 @@ class ContractAdmin extends Controller
view.to = to; view.to = to;
} }
/** /**
* Overview of orders for this contract in backoffice * Overview of orders for this contract in backoffice
*/ */
@@ -527,7 +522,8 @@ class ContractAdmin extends Controller
sendNav(contract); sendNav(contract);
// Checking permissions // Checking permissions
if (!app.user.canManageContract(contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(contract))
throw Error("/", t._("You do not have the authorization to manage this contract"));
if (contract.type == db.Contract.TYPE_VARORDER && args != null && args.d == null) { if (contract.type == db.Contract.TYPE_VARORDER && args != null && args.d == null) {
throw Redirect("/contractAdmin/selectDistrib/" + contract.id); throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
} }
@@ -544,7 +540,6 @@ class ContractAdmin extends Controller
} else { } else {
throw Ok("/contractAdmin/orders/" + contract.id, t._("The order has been deleted.")); throw Ok("/contractAdmin/orders/" + contract.id, t._("The order has been deleted."));
} }
} }
var d = null; var d = null;
@@ -556,7 +551,6 @@ class ContractAdmin extends Controller
var orders = db.UserContract.getOrders(contract, d, app.params.exists("csv")); var orders = db.UserContract.getOrders(contract, d, app.params.exists("csv"));
if (!app.params.exists("csv")) { if (!app.params.exists("csv")) {
// show orders on disabled products // show orders on disabled products
var disabledProducts = 0; var disabledProducts = 0;
for (o in orders) { for (o in orders) {
@@ -569,18 +563,16 @@ class ContractAdmin extends Controller
view.disabledProducts = disabledProducts; view.disabledProducts = disabledProducts;
view.orders = orders; view.orders = orders;
} }
} }
/** /**
* hidden feature : updates orders by setting current product price. * hidden feature : updates orders by setting current product price.
*/ */
function doUpdatePrices(contract:db.Contract, args:{?d:db.Distribution}) { function doUpdatePrices(contract:db.Contract, args:{?d:db.Distribution}) {
sendNav(contract); sendNav(contract);
if (!app.user.canManageContract(contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(contract))
throw Error("/", t._("You do not have the authorization to manage this contract"));
if (contract.type == db.Contract.TYPE_VARORDER && args.d == null) { if (contract.type == db.Contract.TYPE_VARORDER && args.d == null) {
throw Redirect("/contractAdmin/selectDistrib/" + contract.id); throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
} }
@@ -597,7 +589,6 @@ class ContractAdmin extends Controller
o.feesRate = contract.percentageValue; o.feesRate = contract.percentageValue;
} }
o.update(); o.update();
} }
throw Ok("/contractAdmin/orders/" + contract.id + "?d=" + args.d.id, t._("Prices are now up to date.")); throw Ok("/contractAdmin/orders/" + contract.id + "?d=" + args.d.id, t._("Prices are now up to date."));
} }
@@ -607,9 +598,9 @@ class ContractAdmin extends Controller
*/ */
@tpl("form.mtt") @tpl("form.mtt")
function doDuplicate(contract:db.Contract) { function doDuplicate(contract:db.Contract) {
sendNav(contract); sendNav(contract);
if (!app.user.isAmapManager()) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.isAmapManager())
throw Error("/", t._("You do not have the authorization to manage this contract"));
view.title = "Dupliquer le contrat '" + contract.name + "'"; view.title = "Dupliquer le contrat '" + contract.name + "'";
var form = new Form("duplicate"); var form = new Form("duplicate");
@@ -619,7 +610,6 @@ class ContractAdmin extends Controller
form.addElement(new Checkbox("copyDeliveries", t._("Copy deliveries"), true)); form.addElement(new Checkbox("copyDeliveries", t._("Copy deliveries"), true));
if (form.checkToken()) { if (form.checkToken()) {
var nc = new db.Contract(); var nc = new db.Contract();
nc.name = form.getValueOf("name"); nc.name = form.getValueOf("name");
nc.startDate = contract.startDate; nc.startDate = contract.startDate;
@@ -641,7 +631,6 @@ class ContractAdmin extends Controller
ua.giveRight(ContractAdmin(nc.id)); ua.giveRight(ContractAdmin(nc.id));
} }
if (form.getValueOf("copyProducts") == true) { if (form.getValueOf("copyProducts") == true) {
var prods = contract.getProducts(); var prods = contract.getProducts();
for (source_p in prods) { for (source_p in prods) {
@@ -695,27 +684,27 @@ class ContractAdmin extends Controller
view.form = form; view.form = form;
} }
/** /**
* Orders grouped by product * Orders grouped by product
*/ */
@tpl("contractadmin/ordersByProduct.mtt") @tpl("contractadmin/ordersByProduct.mtt")
function doOrdersByProduct(contract:db.Contract, args:{?d:db.Distribution}) { function doOrdersByProduct(contract:db.Contract, args:{?d:db.Distribution}) {
sendNav(contract); sendNav(contract);
if (!app.user.canManageContract(contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(contract))
if (contract.type == db.Contract.TYPE_VARORDER && args.d == null ) throw Redirect("/contractAdmin/selectDistrib/" + contract.id); throw Error("/", t._("You do not have the authorization to manage this contract"));
if (contract.type == db.Contract.TYPE_VARORDER && args.d == null)
throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
var d = args != null ? args.d : null; var d = args != null ? args.d : null;
if (d == null) d = contract.getDistribs(false).first(); if (d == null)
if (d == null) throw Error("/contractAdmin/orders/"+contract.id,t._("There is no delivery in this contract, please create at least one distribution.")); d = contract.getDistribs(false).first();
if (d == null)
throw Error("/contractAdmin/orders/" + contract.id, t._("There is no delivery in this contract, please create at least one distribution."));
var orders = service.ReportService.getOrdersByProduct(d, app.params.exists("csv")); var orders = service.ReportService.getOrdersByProduct(d, app.params.exists("csv"));
view.orders = orders; view.orders = orders;
view.distribution = d; view.distribution = d;
view.c = contract; view.c = contract;
} }
/** /**
@@ -723,17 +712,21 @@ class ContractAdmin extends Controller
*/ */
@tpl("contractadmin/ordersByProductList.mtt") @tpl("contractadmin/ordersByProductList.mtt")
function doOrdersByProductList(contract:db.Contract, args:{?d:db.Distribution}) { function doOrdersByProductList(contract:db.Contract, args:{?d:db.Distribution}) {
sendNav(contract); sendNav(contract);
if (!app.user.canManageContract(contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(contract))
if (contract.type == db.Contract.TYPE_VARORDER && args.d == null ) throw Redirect("/contractAdmin/selectDistrib/" + contract.id); throw Error("/", t._("You do not have the authorization to manage this contract"));
if (contract.type == db.Contract.TYPE_VARORDER && args.d == null)
throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
if (contract.type == db.Contract.TYPE_VARORDER ) view.distribution = args.d; if (contract.type == db.Contract.TYPE_VARORDER)
view.distribution = args.d;
view.c = contract; view.c = contract;
view.group = contract.amap; view.group = contract.amap;
var d = args != null ? args.d : null; var d = args != null ? args.d : null;
if (d == null) d = contract.getDistribs(false).first(); if (d == null)
if (d == null) throw t._("No delivery in this contract"); d = contract.getDistribs(false).first();
if (d == null)
throw t._("No delivery in this contract");
var orders = service.ReportService.getOrdersByProduct(d, false); var orders = service.ReportService.getOrdersByProduct(d, false);
view.orders = orders; view.orders = orders;
@@ -747,18 +740,20 @@ class ContractAdmin extends Controller
view.nav.push("distributions"); view.nav.push("distributions");
sendNav(contract); sendNav(contract);
if (!app.user.canManageContract(contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(contract))
throw Error("/", t._("You do not have the authorization to manage this contract"));
view.c = contract; view.c = contract;
if (args != null && args.old) { if (args != null && args.old) {
// display also old deliveries // display also old deliveries
view.deliveries = contract.getDistribs(false); view.deliveries = contract.getDistribs(false);
} else { } else {
view.deliveries = db.Distribution.manager.search($end > DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 30) && $contract == contract, { orderBy:date} ); view.deliveries = db.Distribution.manager.search($end > DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 30)
&& $contract == contract,
{orderBy: date});
} }
view.cycles = db.DistributionCycle.manager.search($contract == contract && $endDate > Date.now(), false); view.cycles = db.DistributionCycle.manager.search($contract == contract && $endDate > Date.now(), false);
} }
/** /**
@@ -769,16 +764,19 @@ class ContractAdmin extends Controller
view.nav.push("distributions"); view.nav.push("distributions");
sendNav(contract); sendNav(contract);
if (!app.user.canManageContract(contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(contract))
throw Error("/", t._("You do not have the authorization to manage this contract"));
var distribs = contract.getDistribs(false); var distribs = contract.getDistribs(false);
var userCount = new Map<Int, Int>(); var userCount = new Map<Int, Int>();
var suscribers = contract.getUsers(); var suscribers = contract.getUsers();
for( u in suscribers) userCount[u.id] = 0; for (u in suscribers)
userCount[u.id] = 0;
// populate // populate
var increment = function(user:db.User) { var increment = function(user:db.User) {
if(user==null) return; if (user == null)
return;
var x = userCount[user.id]; var x = userCount[user.id];
if (x == null) { if (x == null) {
userCount[user.id] = 1; userCount[user.id] = 1;
@@ -802,7 +800,6 @@ class ContractAdmin extends Controller
} else { } else {
out2.push({user: db.User.manager.get(k), count: userCount[k]}); out2.push({user: db.User.manager.get(k), count: userCount[k]});
} }
} }
var num = (distribs.length * contract.distributorNum) / suscribers.length; var num = (distribs.length * contract.distributorNum) / suscribers.length;
@@ -821,18 +818,20 @@ class ContractAdmin extends Controller
view.nav.push("view"); view.nav.push("view");
sendNav(contract); sendNav(contract);
if (!app.user.canManageContract(contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(contract))
throw Error("/", t._("You do not have the authorization to manage this contract"));
view.c = view.contract = contract; view.c = view.contract = contract;
} }
@tpl("contractadmin/stats.mtt") @tpl("contractadmin/stats.mtt")
function doStats(contract:db.Contract, ?args:{stat:Int}) { function doStats(contract:db.Contract, ?args:{stat:Int}) {
sendNav(contract); sendNav(contract);
if (!app.user.canManageContract(contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(contract))
throw Error("/", t._("You do not have the authorization to manage this contract"));
view.c = contract; view.c = contract;
if (args == null) args = { stat:0 }; if (args == null)
args = {stat: 0};
view.stat = args.stat; view.stat = args.stat;
var pids = contract.getProducts().map(function(x) return x.id); var pids = contract.getProducts().map(function(x) return x.id);
switch (args.stat) { switch (args.stat) {
@@ -842,7 +841,10 @@ class ContractAdmin extends Controller
if (pids.length == 0) { if (pids.length == 0) {
view.anciennete = new List(); view.anciennete = new List();
} else { } else {
view.anciennete = sys.db.Manager.cnx.request("select YEAR(u.cdate) as uyear ,count(DISTINCT u.id) as cnt from User u, UserContract up where up.userId=u.id and up.productId IN (" + pids.join(",") + ") group by uyear;").results(); view.anciennete = sys.db.Manager.cnx.request("select YEAR(u.cdate) as uyear ,count(DISTINCT u.id) as cnt from User u, UserContract up where up.userId=u.id and up.productId IN ("
+ pids.join(",")
+ ") group by uyear;")
.results();
} }
case 1: case 1:
@@ -851,7 +853,10 @@ class ContractAdmin extends Controller
var total = 0; var total = 0;
var totalPrice = 0; var totalPrice = 0;
if (pids.length != 0) { if (pids.length != 0) {
var repartition = sys.db.Manager.cnx.request("select sum(quantity) as quantity,productId,p.name,p.price from UserContract up, Product p where up.productId IN (" + contract.getProducts().map(function(x) return x.id).join(",") + ") and up.productId=p.id group by productId").results(); var repartition = sys.db.Manager.cnx.request("select sum(quantity) as quantity,productId,p.name,p.price from UserContract up, Product p where up.productId IN ("
+ contract.getProducts().map(function(x) return x.id).join(",")
+ ") and up.productId=p.id group by productId")
.results();
for (r in repartition) { for (r in repartition) {
total += r.quantity; total += r.quantity;
totalPrice += r.price * r.quantity; totalPrice += r.price * r.quantity;
@@ -861,32 +866,29 @@ class ContractAdmin extends Controller
} }
if (app.params.exists("csv")) { if (app.params.exists("csv")) {
sugoi.tools.Csv.printCsvDataFromObjects(Lambda.array(repartition), ["quantity","productId","name","price","percent"], "stats-" + contract.name+".csv"); sugoi.tools.Csv.printCsvDataFromObjects(Lambda.array(repartition), ["quantity", "productId", "name", "price", "percent"],
"stats-" + contract.name + ".csv");
} }
} }
view.repartition = repartition; view.repartition = repartition;
view.totalQuantity = total; view.totalQuantity = total;
view.totalPrice = totalPrice; view.totalPrice = totalPrice;
} }
} }
/** /**
* Efface une commande * Efface une commande
* @param uc * @param uc
*/ */
function doDelete(uc:UserContract) { function doDelete(uc:UserContract) {
if (!app.user.canManageContract(uc.product.contract)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(uc.product.contract))
throw Error("/", t._("You do not have the authorization to manage this contract"));
uc.lock(); uc.lock();
uc.delete(); uc.delete();
throw Ok('/contractAdmin/orders/' + uc.product.contract.id, t._("The contract has been canceled")); throw Ok('/contractAdmin/orders/' + uc.product.contract.id, t._("The contract has been canceled"));
} }
@tpl("contractadmin/selectDistrib.mtt") @tpl("contractadmin/selectDistrib.mtt")
function doSelectDistrib(c:db.Contract, ?args:{old:Bool}) { function doSelectDistrib(c:db.Contract, ?args:{old:Bool}) {
view.nav.push("orders"); view.nav.push("orders");
@@ -898,7 +900,6 @@ class ContractAdmin extends Controller
} else { } else {
view.distributions = c.getDistribs(true); view.distributions = c.getDistribs(true);
} }
} }
/** /**
@@ -909,8 +910,10 @@ class ContractAdmin extends Controller
view.nav.push("orders"); view.nav.push("orders");
sendNav(c); sendNav(c);
if (!app.user.canManageContract(c)) throw Error("/", t._("You do not have the authorization to manage this contract")); if (!app.user.canManageContract(c))
if (args.d != null && args.d.validated) throw Error("/contractAdmin/orders/" + c.id + "?d=" + args.d.id, t._("This delivery has been already validated")); throw Error("/", t._("You do not have the authorization to manage this contract"));
if (args.d != null && args.d.validated)
throw Error("/contractAdmin/orders/" + c.id + "?d=" + args.d.id, t._("This delivery has been already validated"));
view.c = view.contract = c; view.c = view.contract = c;
view.u = user; view.u = user;
@@ -918,11 +921,8 @@ class ContractAdmin extends Controller
// need to select a distribution for varying orders contracts // need to select a distribution for varying orders contracts
if (c.type == db.Contract.TYPE_VARORDER && args.d == null) { if (c.type == db.Contract.TYPE_VARORDER && args.d == null) {
throw Redirect("/contractAdmin/orders/" + c.id); throw Redirect("/contractAdmin/orders/" + c.id);
} else { } else {
// members of the group // members of the group
view.users = app.user.amap.getMembersFormElementData(); view.users = app.user.amap.getMembersFormElementData();
@@ -939,13 +939,13 @@ class ContractAdmin extends Controller
order = db.UserContract.manager.select($user == user && $productId == p.id, true); order = db.UserContract.manager.select($user == user && $productId == p.id, true);
} }
if (order != null) ua.order = order; if (order != null)
ua.order = order;
userOrders.push(ua); userOrders.push(ua);
} }
// form check // form check
if (checkToken()) { if (checkToken()) {
// it's a new order, the user has been defined in the form. // it's a new order, the user has been defined in the form.
if (user == null) { if (user == null) {
user = db.User.manager.get(Std.parseInt(app.params.get("user"))); user = db.User.manager.get(Std.parseInt(app.params.get("user")));
@@ -953,7 +953,8 @@ class ContractAdmin extends Controller
var user = app.params.get("user"); var user = app.params.get("user");
throw t._("Unable to find user #::num::", {num: user}); throw t._("Unable to find user #::num::", {num: user});
} }
if (!user.isMemberOf(app.user.amap)) throw user + " is not member of this group"; if (!user.isMemberOf(app.user.amap))
throw user + " is not member of this group";
} }
// get distrib if needed // get distrib if needed
@@ -967,11 +968,11 @@ class ContractAdmin extends Controller
for (k in app.params.keys()) { for (k in app.params.keys()) {
var param = app.params.get(k); var param = app.params.get(k);
if (k.substr(0, "product".length) == "product") { if (k.substr(0, "product".length) == "product") {
// trouve le produit dans userOrders // trouve le produit dans userOrders
var pid = Std.parseInt(k.substr("product".length)); var pid = Std.parseInt(k.substr("product".length));
var uo = Lambda.find(userOrders, function(uo) return uo.product.id == pid); var uo = Lambda.find(userOrders, function(uo) return uo.product.id == pid);
if (uo == null) throw t._("Unable to find product ::pid::", {pid:pid}); if (uo == null)
throw t._("Unable to find product ::pid::", {pid: pid});
// user2 ? // user2 ?
var user2:db.User = null; var user2:db.User = null;
@@ -982,8 +983,10 @@ class ContractAdmin extends Controller
var user = app.params.get("user2"); var user = app.params.get("user2");
throw t._("Unable to find user #::num::", {num: user}); throw t._("Unable to find user #::num::", {num: user});
} }
if (!user2.isMemberOf(app.user.amap)) throw t._("::user:: is not part of this group",{user:user2}); if (!user2.isMemberOf(app.user.amap))
if (user.id == user2.id) throw t._("Both selected accounts must be different ones"); throw t._("::user:: is not part of this group", {user: user2});
if (user.id == user2.id)
throw t._("Both selected accounts must be different ones");
invert = app.params.get("invert" + pid) == "1"; invert = app.params.get("invert" + pid) == "1";
} }
@@ -996,17 +999,21 @@ class ContractAdmin extends Controller
} else { } else {
q = Std.parseInt(param); q = Std.parseInt(param);
} }
if(q==null) continue; //ignore bad qt input if (q == null)
continue; // ignore bad qt input
// record order // record order
if (uo.order != null) { if (uo.order != null) {
// existing record // existing record
var o = OrderService.edit(uo.order, q, (app.params.get("paid" + pid) == "1"), user2, invert); var o = OrderService.edit(uo.order, q, (app.params.get("paid" + pid) == "1"), user2, invert);
if (o != null) orders.push(o); if (o != null)
orders.push(o);
} else { } else {
// new record // new record
var o = OrderService.make(user, q, uo.product, distrib == null ? null : distrib.id, (app.params.get("paid" + pid) == "1"), user2, invert); var o = OrderService.make(user, q, uo.product, distrib == null ? null : distrib.id, (app.params.get("paid" + pid) == "1"), user2,
if (o != null) orders.push(o); invert);
if (o != null)
orders.push(o);
} }
} }
} }
@@ -1023,5 +1030,4 @@ class ContractAdmin extends Controller
view.userOrders = userOrders; view.userOrders = userOrders;
} }
} }
} }
+71 -57
View File
@@ -1,18 +1,15 @@
package controller; package controller;
import sugoi.db.Cache; import sugoi.db.Cache;
import sugoi.Web; import sugoi.Web;
import sugoi.mail.Mail; import sugoi.mail.Mail;
import Common; import Common;
using Lambda; using Lambda;
using tools.DateTool; using tools.DateTool;
class Cron extends Controller class Cron extends Controller {
{ public function doDefault() {}
public function doDefault()
{
}
/** /**
* CLI only en prod * CLI only en prod
@@ -23,7 +20,6 @@ class Cron extends Controller
} else if (App.config.DEBUG) { } else if (App.config.DEBUG) {
return true; return true;
} else { } else {
if (Web.isModNeko) { if (Web.isModNeko) {
Sys.print("only CLI."); Sys.print("only CLI.");
return false; return false;
@@ -34,15 +30,14 @@ class Cron extends Controller
} }
public function doMinute() { public function doMinute() {
print("Cron.doMinute is called"); print("Cron.doMinute is called");
if (!canRun()) return; if (!canRun())
return;
app.event(MinutelyCron); app.event(MinutelyCron);
sendEmailsfromBuffer(); sendEmailsfromBuffer();
} }
/** /**
@@ -51,7 +46,6 @@ class Cron extends Controller
* this function can be locally tested with `neko index.n cron/hour > cron.log` * this function can be locally tested with `neko index.n cron/hour > cron.log`
*/ */
public function doHour() { public function doHour() {
app.event(HourlyCron); app.event(HourlyCron);
distribNotif(4, db.User.UserFlags.HasEmailNotif4h); // 4h before distribNotif(4, db.User.UserFlags.HasEmailNotif4h); // 4h before
@@ -62,9 +56,9 @@ class Cron extends Controller
// sendOrdersByProductWhenOrdersClose(); // sendOrdersByProductWhenOrdersClose();
} }
public function doDaily() { public function doDaily() {
if (!canRun()) return; if (!canRun())
return;
app.event(DailyCron); app.event(DailyCron);
@@ -78,7 +72,8 @@ class Cron extends Controller
var report = new StringBuf(); var report = new StringBuf();
report.add("<h1>" + App.config.NAME + " : ERRORS</h1>"); report.add("<h1>" + App.config.NAME + " : ERRORS</h1>");
for (e in errors) { for (e in errors) {
report.add("<div><pre>"+e.error + " at URL " + e.url + " ( user : " + (e.user!=null?e.user.toString():"none") + ", IP : " + e.ip + ")</pre></div><hr/>"); report.add("<div><pre>" + e.error + " at URL " + e.url + " ( user : " + (e.user != null ? e.user.toString() : "none") + ", IP : " + e.ip
+ ")</pre></div><hr/>");
} }
var m = new Mail(); var m = new Mail();
@@ -89,11 +84,11 @@ class Cron extends Controller
App.sendMail(m); App.sendMail(m);
} }
// DEMO CONTRATS deletion after 7 days ( see controller.Group.doCreate() ) // DEMO CONTRATS deletion after 7 days ( see controller.Group.doCreate() )
db.Contract.manager.delete($name == "Contrat AMAP Maraîcher Exemple" && $startDate < DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 7)); db.Contract.manager.delete($name == "Contrat AMAP Maraîcher Exemple"
db.Contract.manager.delete($name == "Contrat Poulet Exemple" && $startDate < DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 7)); && $startDate < DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 7));
db.Contract.manager.delete($name == "Contrat Poulet Exemple"
&& $startDate < DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 7));
// Old Messages cleaning // Old Messages cleaning
db.Message.manager.delete($date < DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 30 * 6)); db.Message.manager.delete($date < DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 30 * 6));
@@ -107,8 +102,6 @@ class Cron extends Controller
u.email2 = null; u.email2 = null;
u.update(); u.update();
}*/ }*/
} }
/** /**
@@ -117,7 +110,6 @@ class Cron extends Controller
* @param flag * @param flag
*/ */
function distribNotif(hour:Int, flag:db.User.UserFlags) { function distribNotif(hour:Int, flag:db.User.UserFlags) {
// trouve les distrib qui commencent dans le nombre d'heures demandé // trouve les distrib qui commencent dans le nombre d'heures demandé
// on recherche celles qui commencent jusqu'à une heure avant pour ne pas en rater // on recherche celles qui commencent jusqu'à une heure avant pour ne pas en rater
var from = DateTools.delta(Date.now(), 1000.0 * 60 * 60 * (hour - 1)); var from = DateTools.delta(Date.now(), 1000.0 * 60 * 60 * (hour - 1));
@@ -136,7 +128,8 @@ class Cron extends Controller
// Sys.print("distribNotif "+hour+" from "+from+" to "+to+"<br/>\n"); // Sys.print("distribNotif "+hour+" from "+from+" to "+to+"<br/>\n");
// on s'arrete immédiatement si aucune distibution trouvée // on s'arrete immédiatement si aucune distibution trouvée
if (distribs.length == 0) return; if (distribs.length == 0)
return;
// cherche plus tard si on a pas une "grappe" de distrib // cherche plus tard si on a pas une "grappe" de distrib
/*while (true) { /*while (true) {
@@ -170,25 +163,30 @@ class Cron extends Controller
} }
// toutes les distribs trouvées ont deja été traitées // toutes les distribs trouvées ont deja été traitées
if (distribs.length == 0) return; if (distribs.length == 0)
return;
// stocke cache // stocke cache
for (d in distribs) dist.push(d.id); for (d in distribs)
dist.push(d.id);
Cache.set(cacheId, dist, 24 * 60 * 60); Cache.set(cacheId, dist, 24 * 60 * 60);
// We have now the distribs we want to notify about. // We have now the distribs we want to notify about.
var distribsByContractId = new Map<Int, db.Distribution>(); var distribsByContractId = new Map<Int, db.Distribution>();
for (d in distribs) { for (d in distribs) {
if (d == null || d.contract==null) continue; if (d == null || d.contract == null)
continue;
distribsByContractId.set(d.contract.id, d); distribsByContractId.set(d.contract.id, d);
} }
// Boucle sur les distributions pour gerer le cas de plusieurs distributions le même jour sur le même contrat // Boucle sur les distributions pour gerer le cas de plusieurs distributions le même jour sur le même contrat
var orders = []; var orders = [];
for (d in distribs) { for (d in distribs) {
if (d == null || d.contract==null) continue; if (d == null || d.contract == null)
continue;
// get orders for both type of contracts // get orders for both type of contracts
for ( x in d.contract.getOrders(d)) orders.push(x); for (x in d.contract.getOrders(d))
orders.push(x);
} }
/* /*
@@ -203,9 +201,14 @@ class Cron extends Controller
}>(); }>();
for (o in orders) { for (o in orders) {
var x = users.get(o.user.id + "-" + o.product.contract.amap.id); var x = users.get(o.user.id + "-" + o.product.contract.amap.id);
if (x == null) x = {user:o.user,distrib:null,products:[],vendors:[]}; if (x == null)
x = {
user: o.user,
distrib: null,
products: [],
vendors: []
};
x.distrib = distribsByContractId.get(o.product.contract.id); x.distrib = distribsByContractId.get(o.product.contract.id);
x.products.push(o); x.products.push(o);
users.set(o.user.id + "-" + o.product.contract.amap.id, x); users.set(o.user.id + "-" + o.product.contract.amap.id, x);
@@ -214,7 +217,13 @@ class Cron extends Controller
// Prévenir également le deuxième user en cas des commandes alternées // Prévenir également le deuxième user en cas des commandes alternées
if (o.user2 != null) { if (o.user2 != null) {
var x = users.get(o.user2.id + "-" + o.product.contract.amap.id); var x = users.get(o.user2.id + "-" + o.product.contract.amap.id);
if (x == null) x = {user:o.user2,distrib:null,products:[],vendors:[]}; if (x == null)
x = {
user: o.user2,
distrib: null,
products: [],
vendors: []
};
x.distrib = distribsByContractId.get(o.product.contract.id); x.distrib = distribsByContractId.get(o.product.contract.id);
x.products.push(o); x.products.push(o);
users.set(o.user2.id + "-" + o.product.contract.amap.id, x); users.set(o.user2.id + "-" + o.product.contract.amap.id, x);
@@ -226,18 +235,25 @@ class Cron extends Controller
for (k in users.keys()) { for (k in users.keys()) {
var x = users.get(k); var x = users.get(k);
var total = 0.0; var total = 0.0;
for( o in x.products) total += o.quantity; for (o in x.products)
if(total==0.0) users.remove(k); total += o.quantity;
if (total == 0.0)
users.remove(k);
} }
// Dans le cas de l'ouverture de commande, ce sont tous les users qu'il faut intégrer // Dans le cas de l'ouverture de commande, ce sont tous les users qu'il faut intégrer
if ( db.User.UserFlags.HasEmailNotifOuverture == flag ) if (db.User.UserFlags.HasEmailNotifOuverture == flag) {
{
for (d in distribs) { for (d in distribs) {
var memberList = d.contract.amap.getMembers(); var memberList = d.contract.amap.getMembers();
for (u in memberList) { for (u in memberList) {
var x = users.get(u.id + "-" + d.contract.amap.id); var x = users.get(u.id + "-" + d.contract.amap.id);
if (x == null) x = {user:u,distrib:null,products:[],vendors:[]}; if (x == null)
x = {
user: u,
distrib: null,
products: [],
vendors: []
};
x.distrib = distribsByContractId.get(d.contract.id); x.distrib = distribsByContractId.get(d.contract.id);
x.vendors.push(d.contract.vendor); x.vendors.push(d.contract.vendor);
users.set(u.id + "-" + d.contract.amap.id, x); users.set(u.id + "-" + d.contract.amap.id, x);
@@ -247,16 +263,13 @@ class Cron extends Controller
} }
for (u in users) { for (u in users) {
if (u.user.flags.has(flag)) { if (u.user.flags.has(flag)) {
if (u.user.email != null) { if (u.user.email != null) {
var group = u.distrib.contract.amap; var group = u.distrib.contract.amap;
this.t = sugoi.i18n.Locale.init(u.user.lang); // switch to the user language this.t = sugoi.i18n.Locale.init(u.user.lang); // switch to the user language
var text; var text;
if ( db.User.UserFlags.HasEmailNotifOuverture == flag ) if (db.User.UserFlags.HasEmailNotifOuverture == flag) {
{
// order opening notif // order opening notif
text = t._("Opening of orders for the delivery of <b>::date::</b>", {date: view.hDate(u.distrib.date)}); text = t._("Opening of orders for the delivery of <b>::date::</b>", {date: view.hDate(u.distrib.date)});
text += "<br/>"; text += "<br/>";
@@ -266,11 +279,11 @@ class Cron extends Controller
text += "<li>" + v + "</li>"; text += "<li>" + v + "</li>";
} }
text += "</ul>"; text += "</ul>";
} else { } else {
// Distribution notif to the users // Distribution notif to the users
var d = u.distrib; var d = u.distrib;
text = t._("Do not forget the delivery on <b>::day::</b> from ::from:: to ::to::<br/>", {day:view.dDate(d.date),from:view.hHour(d.date),to:view.hHour(d.end)}); text = t._("Do not forget the delivery on <b>::day::</b> from ::from:: to ::to::<br/>",
{day: view.dDate(d.date), from: view.hHour(d.date), to: view.hHour(d.end)});
text += t._("Your products to collect :") + "<br/><ul>"; text += t._("Your products to collect :") + "<br/><ul>";
for (p in u.products) { for (p in u.products) {
text += "<li>" + p.quantity + " x " + p.product.getName(); text += "<li>" + p.quantity + " x " + p.product.getName();
@@ -294,29 +307,28 @@ class Cron extends Controller
try { try {
var m = new Mail(); var m = new Mail();
m.setSender(App.config.get("default_email"), "Cagette.net"); m.setSender(App.config.get("default_email"), "Cagette.net");
if(group.contact!=null) m.setReplyTo(group.contact.email, group.name); if (group.contact != null)
m.setReplyTo(group.contact.email, group.name);
m.addRecipient(u.user.email, u.user.getName()); m.addRecipient(u.user.email, u.user.getName());
if (u.user.email2 != null) m.addRecipient(u.user.email2); if (u.user.email2 != null)
m.addRecipient(u.user.email2);
m.setSubject(group.name + " : " + t._("Distribution on ::date::", {date: app.view.hDate(u.distrib.date)})); m.setSubject(group.name + " : " + t._("Distribution on ::date::", {date: app.view.hDate(u.distrib.date)}));
m.setHtmlBody(app.processTemplate("mail/message.mtt", {text: text, group: group})); m.setHtmlBody(app.processTemplate("mail/message.mtt", {text: text, group: group}));
App.sendMail(m, u.distrib.contract.amap); App.sendMail(m, u.distrib.contract.amap);
} catch (e:Dynamic) { } catch (e:Dynamic) {
app.logError(e); // email could be invalid app.logError(e); // email could be invalid
} }
} }
} }
} }
} }
/** /**
* Check if there is a multi-distrib to validate. * Check if there is a multi-distrib to validate.
* *
* Autovalidate it after 10 days * Autovalidate it after 10 days
*/ */
function distribValidationNotif() { function distribValidationNotif() {
var now = Date.now(); var now = Date.now();
var from = now.setHourMinute(now.getHours(), 0); var from = now.setHourMinute(now.getHours(), 0);
@@ -350,7 +362,8 @@ class Cron extends Controller
var html = t._("<p>Your distribution just finished, don't forget to <b>validate</b> it</p>"); var html = t._("<p>Your distribution just finished, don't forget to <b>validate</b> it</p>");
html += explain; html += explain;
html += t._("<p><a href='::distriburl::'>Click here to validate the distribution</a> (You must be connected to your group Cagette)", {distriburl:url}); html += t._("<p><a href='::distriburl::'>Click here to validate the distribution</a> (You must be connected to your group Cagette)",
{distriburl: url});
App.quickMail(d.contract.amap.contact.email, subj, html); App.quickMail(d.contract.amap.contact.email, subj, html);
} }
@@ -383,12 +396,12 @@ class Cron extends Controller
var html = t._("<p>Reminder: you have a delivery to validate.</p>"); var html = t._("<p>Reminder: you have a delivery to validate.</p>");
html += explain; html += explain;
html += t._("<p><a href='::distriburl::'>Click here to validate the delivery</a> (You must be connected to your Cagette group)", {distriburl:url}); html += t._("<p><a href='::distriburl::'>Click here to validate the delivery</a> (You must be connected to your Cagette group)",
{distriburl: url});
App.quickMail(d.contract.amap.contact.email, subj, html); App.quickMail(d.contract.amap.contact.email, subj, html);
} }
/* /*
* Autovalidate unvalidated distributions after 10 days * Autovalidate unvalidated distributions after 10 days
*/ */
@@ -408,17 +421,18 @@ class Cron extends Controller
print(d.toString()); print(d.toString());
service.PaymentService.validateDistribution(d); service.PaymentService.validateDistribution(d);
} }
// email // email
var ds = tools.ObjectListTool.deduplicateDistribsByKey(ds); var ds = tools.ObjectListTool.deduplicateDistribsByKey(ds);
for (d in ds) { for (d in ds) {
// var subj = d.contract.amap.name + t._(": Validation of the distribution of the ") + App.current.view.hDate(d.date); // var subj = d.contract.amap.name + t._(": Validation of the distribution of the ") + App.current.view.hDate(d.date);
var subj = t._("[::group::] Validation of the ::date:: distribution", {group: d.contract.amap.name, date: view.hDate(d.date)}); var subj = t._("[::group::] Validation of the ::date:: distribution", {group: d.contract.amap.name, date: view.hDate(d.date)});
var html = t._("<p>As you did not validate it manually after 10 days, <br/>the delivery of the ::deliveryDate:: has been validated automatically</p>", {deliveryDate:App.current.view.hDate(d.date)}); var html = t._("<p>As you did not validate it manually after 10 days, <br/>the delivery of the ::deliveryDate:: has been validated automatically</p>",
{
deliveryDate: App.current.view.hDate(d.date)
});
App.quickMail(d.contract.amap.contact.email, subj, html); App.quickMail(d.contract.amap.contact.email, subj, html);
} }
} }
/** /**
@@ -429,13 +443,16 @@ class Cron extends Controller
* (like "SELECT * FROM BufferedMail WHERE sdate IS NULL ORDER BY cdate DESC LIMIT 100 FOR UPDATE Lock wait timeout exceeded; try restarting transaction") * (like "SELECT * FROM BufferedMail WHERE sdate IS NULL ORDER BY cdate DESC LIMIT 100 FOR UPDATE Lock wait timeout exceeded; try restarting transaction")
*/ */
function sendEmailsfromBuffer() { function sendEmailsfromBuffer() {
App.log("Send Emails from Buffer");
print("<h3>Send Emails from Buffer</h3>"); print("<h3>Send Emails from Buffer</h3>");
// send // send
for (e in sugoi.db.BufferedMail.manager.search($sdate == null, {limit: 50, orderBy: -cdate}, false)) { for (e in sugoi.db.BufferedMail.manager.search($sdate == null, {limit: 50, orderBy: -cdate}, false)) {
e.lock(); e.lock();
if(e.isSent()) continue; if (e.isSent())
continue;
App.log('Send Email id=${e.id} - title=${e.title}');
print('#${e.id} - ${e.title}'); print('#${e.id} - ${e.title}');
e.finallySend(); e.finallySend();
Sys.sleep(0.1); Sys.sleep(0.1);
@@ -459,7 +476,6 @@ class Cron extends Controller
* Email product report when orders close * Email product report when orders close
**/ **/
function sendOrdersByProductWhenOrdersClose() { function sendOrdersByProductWhenOrdersClose() {
var range = tools.DateTool.getLastHourRange(); var range = tools.DateTool.getLastHourRange();
// Sys.println("Time is "+Date.now()+"<br/>"); // Sys.println("Time is "+Date.now()+"<br/>");
// Sys.println('Find all distributions that have closed in the last hour from ${range.from} to ${range.to} \n<br/>'); // Sys.println('Find all distributions that have closed in the last hour from ${range.from} to ${range.to} \n<br/>');
@@ -467,10 +483,8 @@ class Cron extends Controller
for (d in db.Distribution.manager.search($orderEndDate >= range.from && $orderEndDate < range.to, false)) { for (d in db.Distribution.manager.search($orderEndDate >= range.from && $orderEndDate < range.to, false)) {
service.OrderService.sendOrdersByProductReport(d); service.OrderService.sendOrdersByProductReport(d);
} }
} }
function print(text) { function print(text) {
Sys.println(text + "<br/>"); Sys.println(text + "<br/>");
} }
+59 -38
View File
@@ -1,22 +1,20 @@
package controller; package controller;
import db.Message; import db.Message;
import db.UserContract; import db.UserContract;
import sugoi.form.ListData; import sugoi.form.ListData;
import sugoi.form.elements.*; import sugoi.form.elements.*;
import sugoi.form.Form; import sugoi.form.Form;
class Messages extends Controller class Messages extends Controller {
{ public function new() {
public function new()
{
super(); super();
if (!app.user.canAccessMessages()) throw Redirect("/"); if (!app.user.canAccessMessages())
throw Redirect("/");
} }
@tpl("messages/default.mtt") @tpl("messages/default.mtt")
function doDefault() { function doDefault() {
var form = new Form("msg"); var form = new Form("msg");
var senderName = ""; var senderName = "";
@@ -25,7 +23,6 @@ class Messages extends Controller
if (App.current.session.data.whichUser == 1 && app.user.email2 != null) { if (App.current.session.data.whichUser == 1 && app.user.email2 != null) {
senderMail = app.user.email2; senderMail = app.user.email2;
senderName = app.user.firstName2 + " " + app.user.lastName2; senderName = app.user.firstName2 + " " + app.user.lastName2;
} else { } else {
senderMail = app.user.email; senderMail = app.user.email;
senderName = app.user.firstName + " " + app.user.lastName; senderName = app.user.firstName + " " + app.user.lastName;
@@ -39,42 +36,75 @@ class Messages extends Controller
form.addElement(new TextArea("text", t._("Message:"), "", false, null, "style='width:500px;height:350px;'")); form.addElement(new TextArea("text", t._("Message:"), "", false, null, "style='width:500px;height:350px;'"));
if (form.checkToken()) { if (form.checkToken()) {
var listId = form.getElement("list").value; var listId = form.getElement("list").value;
var dest = getSelection(listId); var dest = getSelection(listId);
var subject = form.getValueOf("subject");
App.log('about to send email <$subject> to listId=<$listId> to ${dest.length} recipient(s)');
// Sys.command("sh", [
// "-c",
// "sendemail -f no-reply@comptoirduvrac.re -s mail1.zourit.net:587 -t pvincent@comptoirduvrac.re -bcc 'pvincent974@gmail.com, pvincent974@laposte.net' -u TEST -m coucou -xu postmaster@comptoirduvrac.re -xp QqQeAPT6EpoK"
// ]);
var mails = []; var mails = [];
for (d in dest) { for (d in dest) {
if (d.email != null) mails.push(d.email); if (d.email != null)
if (d.email2 != null) mails.push(d.email2); mails.push(d.email);
if (d.email2 != null)
mails.push(d.email2);
} }
// send mail confirmation link // send mail confirmation link
var e = new sugoi.mail.Mail(); var e = new sugoi.mail.Mail();
e.setSubject(form.getValueOf("subject")); e.setSender(App.config.get("default_email"));
for ( x in mails) e.addRecipient(x); e.setSubject(subject);
var replyTo = form.getValueOf("senderMail");
var replyToName = form.getValueOf("senderName");
if (replyTo != null)
e.setReplyTo(replyTo, replyToName);
if (mails.length > 1) {
var cc = mails.join(",");
App.log('add header Cc: $cc');
e.setHeader("CC:", cc);
// for (x in mails)
// e.addRecipient(x);
e.addRecipient(e.getSender().email);
} else {
App.log('no header');
e.addRecipient(mails[0]);
}
e.setSender(App.config.get("default_email"),form.getValueOf("senderName"));
e.setReplyTo(form.getValueOf("senderMail"),form.getValueOf("senderName"));
// sender : default email ( explicitly tells that the server send an email on behalf of the user ) // sender : default email ( explicitly tells that the server send an email on behalf of the user )
// e.setHeader("Sender", App.config.get("default_email")); // e.setHeader("Sender", App.config.get("default_email"));
var text:String = form.getValueOf("text"); var text:String = form.getValueOf("text");
var html = app.processTemplate("mail/message.mtt", {text: text, group: app.user.amap, list: getListName(listId)}); var html = app.processTemplate("mail/message.mtt", {text: text, group: app.user.amap, list: getListName(listId)});
e.setHtmlBody(html); e.setHtmlBody(html);
App.sendMail(e,app.user.getAmap(),listId,app.user); // App.sendMail(e, app.user.getAmap(), listId, app.user);
// Sys.command("sendemail", [
// "-f", "no-reply@comptoirduvrac.re", "-s", "mail1.zourit.net:587", "-t", "pvincent@comptoirduvrac.re", "-bcc",
// "pvincent974@gmail.com,pvincent974@laposte.net", "-u", subject, "-m", "alors tout va bien", "-xu", "postmaster@comptoirduvrac.re", "-xp",
// "QqQeAPT6EpoK"
// ]);
sys.io.File.saveContent('/tmp/my_file.json', "CONTENT");
// store message // store message
var lm = new db.Message(); var lm = new db.Message();
lm.amap = app.user.amap; lm.amap = app.user.amap;
lm.recipients = Lambda.array(Lambda.map(e.getRecipients(), function(x) return x.email)); // lm.recipients = Lambda.array(Lambda.map(e.getRecipients(), function(x) return x.email));
lm.recipients = mails;
lm.title = e.getSubject(); lm.title = e.getSubject();
lm.date = Date.now(); lm.date = Date.now();
lm.body = e.getHtmlBody(); lm.body = e.getHtmlBody();
if (listId != null) lm.recipientListId = listId; if (listId != null)
lm.recipientListId = listId;
lm.sender = app.user; lm.sender = app.user;
lm.insert(); lm.insert();
throw Ok("/messages", t._("The message has been sent")); throw Ok("/messages", t._("The message has been sent"));
} }
@@ -83,15 +113,15 @@ class Messages extends Controller
if (app.user.isAmapManager()) { if (app.user.isAmapManager()) {
view.sentMessages = Message.manager.search($amap == app.user.amap && $recipientListId != null, {orderBy: -date, limit: 20}, false); view.sentMessages = Message.manager.search($amap == app.user.amap && $recipientListId != null, {orderBy: -date, limit: 20}, false);
} else { } else {
view.sentMessages = Message.manager.search($sender == app.user && $recipientListId!=null && $amap == app.user.amap , {orderBy:-date,limit:20}, false); view.sentMessages = Message.manager.search($sender == app.user && $recipientListId != null && $amap == app.user.amap, {orderBy: -date, limit: 20},
false);
} }
} }
@tpl("messages/message.mtt") @tpl("messages/message.mtt")
public function doMessage(msg:Message) { public function doMessage(msg:Message) {
if (!app.user.isAmapManager() && msg.sender.id != app.user.id)
if (!app.user.isAmapManager() && msg.sender.id != app.user.id) throw Error("/", t._("Non authorized access")); throw Error("/", t._("Non authorized access"));
view.list = getListName(msg.recipientListId); view.list = getListName(msg.recipientListId);
view.msg = msg; view.msg = msg;
@@ -106,7 +136,6 @@ class Messages extends Controller
}*/ }*/
view.status = s; view.status = s;
} }
function getLists():FormData<String> { function getLists():FormData<String> {
@@ -117,8 +146,8 @@ class Messages extends Controller
out.push({value: '3', label: t._("TEST: me + spouse")}); out.push({value: '3', label: t._("TEST: me + spouse")});
out.push({value: '4', label: t._("Members without contract/order")}); out.push({value: '4', label: t._("Members without contract/order")});
if(app.user.amap.hasMembership()) out.push( { value:'5', label:t._("Memberships to be renewed")} ); if (app.user.amap.hasMembership())
out.push({value: '5', label: t._("Memberships to be renewed")});
var contracts = db.Contract.getActiveContracts(app.user.amap, true); var contracts = db.Contract.getActiveContracts(app.user.amap, true);
for (c in contracts) { for (c in contracts) {
@@ -126,7 +155,6 @@ class Messages extends Controller
out.push({value: 'c' + c.id, label: label}); out.push({value: 'c' + c.id, label: label});
} }
return out; return out;
} }
/** /**
@@ -137,11 +165,11 @@ class Messages extends Controller
var l = getLists(); var l = getLists();
for (ll in l) { for (ll in l) {
if (ll.value == listId) return ll.label; if (ll.value == listId)
return ll.label;
} }
return null; return null;
} }
function getSelection(listId:String) { function getSelection(listId:String) {
@@ -153,7 +181,6 @@ class Messages extends Controller
var pids = Lambda.map(pids, function(x) return x.id); var pids = Lambda.map(pids, function(x) return x.id);
var up = db.UserContract.manager.search($productId in pids, false); var up = db.UserContract.manager.search($productId in pids, false);
var users = []; var users = [];
for (order in up) { for (order in up) {
if (!Lambda.has(users, order.user)) { if (!Lambda.has(users, order.user)) {
@@ -164,7 +191,6 @@ class Messages extends Controller
} }
} }
return users; return users;
} else { } else {
var out = []; var out = [];
switch (listId) { switch (listId) {
@@ -184,7 +210,8 @@ class Messages extends Controller
// ajouter les autres personnes ayant les droits Admin ou Gestion Adhérents ou Gestion Contrats // ajouter les autres personnes ayant les droits Admin ou Gestion Adhérents ou Gestion Contrats
for (ua in Lambda.array(db.UserAmap.manager.search($rights != null && $amap == app.user.amap, false))) { for (ua in Lambda.array(db.UserAmap.manager.search($rights != null && $amap == app.user.amap, false))) {
if (ua.hasRight(GroupAdmin) || ua.hasRight(Membership) || ua.hasRight(ContractAdmin())) { if (ua.hasRight(GroupAdmin) || ua.hasRight(Membership) || ua.hasRight(ContractAdmin())) {
if (!Lambda.has(users, ua.user)) users.push(ua.user); if (!Lambda.has(users, ua.user))
users.push(ua.user);
} }
} }
@@ -200,12 +227,6 @@ class Messages extends Controller
} }
return out; return out;
} }
} }
} }