Compare commits

..
15 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
cagettepei.lxd bbeea934e4 tagged as 1.7.2 2021-08-25 19:10:48 +04:00
cagettepei.lxd 3c8a2507d9 no package-lock.json 2021-08-25 19:10:35 +04:00
cagettepei.lxd 6c0e632ef2 tagged as 1.7.1 2021-08-25 19:06:37 +04:00
cagettepei.lxd f94e005a91 fix Makefile 2021-08-25 19:06:24 +04:00
10 changed files with 1055 additions and 7206 deletions
+3 -3
View File
@@ -1,7 +1,7 @@
*.n
*.php
config.xml
/package-lock.json
package-lock.json
www/plugin/*
tmp/*
*node_modules*
@@ -30,9 +30,9 @@ www/file/*
www/js/app.js
www/js/libs.js
www/css/.sass-cache
www/css/*.css
!www/css/bootstrap.min.css
config-dev.xml
config-prod.xml
+1 -1
View File
@@ -1 +1 @@
1.7.0
1.8.2
+1 -3
View File
@@ -26,9 +26,6 @@ install_dev:
#template tools
haxelib run templo
sudo mv temploc2 /usr/bin
#extra plugins
@if [ $(PLUGINS) = 1 ]; then \
fi
#install npm dependencies
npm install
npm run libs:dev
@@ -77,6 +74,7 @@ templates:
@make LANG=fr ctemplates
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 lang
ctemplates:
(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)
* 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 sudo haxe apache2 make git imagemagick gettext libapache2-mod-neko mariadb-server
* mysql -u root <<EOF
@@ -28,6 +28,8 @@ EOF
ServerName cagettepei
DirectoryIndex index.n
DocumentRoot /var/www/cagettepei/www/
</VirtualHost>
```
* sed -i '/<Directory \/var\/www\/>/,/<\/Directory>/ s/AllowOverride None/AllowOverride All/' /etc/apache2/apache2.conf
-6188
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -47,5 +47,5 @@
"bugs": {
"url": "https://github.com/bablukid/cagette/issues"
},
"version": "1.7.0"
"version": "1.8.2"
}
+22 -26
View File
@@ -3,7 +3,6 @@ import thx.semver.Version;
import Common;
class App extends sugoi.BaseApp {
public static var current:App = null;
public static var t:sugoi.i18n.translator.ITranslator;
public static var config = sugoi.BaseApp.config;
@@ -24,7 +23,6 @@ class App extends sugoi.BaseApp {
}
public static function main() {
App.t = sugoi.form.Form.translator = new sugoi.i18n.translator.TMap(getTranslationArray(), "fr");
sugoi.BaseApp.main();
}
@@ -51,8 +49,10 @@ class App extends sugoi.BaseApp {
}
public function getCurrentGroup() {
if (session == null) return null;
if (session.data == null ) return null;
if (session == null)
return null;
if (session.data == null)
return null;
var a = session.data.amapId;
if (a == null) {
return null;
@@ -62,7 +62,6 @@ class App extends sugoi.BaseApp {
}
override function beforeDispatch() {
// send "current page" event
event(Page(this.uri));
@@ -71,22 +70,22 @@ class App extends sugoi.BaseApp {
public function getPlugin(name:String):sugoi.plugin.IPlugIn {
for (p in plugins) {
if (p.getName() == name) return p;
if (p.getName() == name)
return p;
}
return null;
}
public static function log(t:Dynamic) {
if(App.config.DEBUG) {
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/)
#end
}
public static function log(t:Dynamic, ?infos:haxe.PosInfos) {
// if (App.config.DEBUG) {
// neko.Web.logMessage(Std.string(t)); // write in Apache error log
// }
neko.Web.logMessage('[${infos.fileName}:${infos.lineNumber} ${infos.className}#${infos.methodName}] ' + Std.string(t));
}
public function event(e:Event) {
if(e==null) return null;
if (e == null)
return null;
this.eventDispatcher.dispatch(e);
return e;
}
@@ -231,15 +230,12 @@ class App extends sugoi.BaseApp {
}
public static function getMailer():sugoi.mail.IMailer {
var mailer:sugoi.mail.IMailer = new sugoi.mail.BufferedMailer();
if (App.config.DEBUG) {
//Dev env : emails are written to tmp folder
App.log("DEBUGEmailer enabled => emails are written to tmp folder");
mailer = new sugoi.mail.DebugMailer();
} else {
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>");
throw sugoi.ControllerAction.ErrorAction("/", msg);
@@ -260,18 +256,21 @@ class App extends sugoi.BaseApp {
* Send an email
*/
public static function sendMail(m:sugoi.mail.Mail, ?group:db.Amap, ?listId:String, ?sender:db.User) {
if (group == null) group = App.current.user == null ? null:App.current.user.getAmap();
if (group == null)
group = App.current.user == null ? null : App.current.user.getAmap();
current.event(SendEmail(m));
var params = group == null ? null : {remoteId: group.id};
App.log('about to send email with subject=<${m.getSubject()}> ...');
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) {
App.log('quickMail subject=$subject');
var e = new sugoi.mail.Mail();
e.setSubject(subject);
e.setRecipient(to);
@@ -287,7 +286,6 @@ class App extends sugoi.BaseApp {
* @param ctx
*/
public function processTemplate(tpl:String, ctx:Dynamic):String {
Reflect.setField(ctx, 'HOST', App.config.HOST);
Reflect.setField(ctx, 'hDate', App.current.view.hDate);
// i18n functions
@@ -297,11 +295,9 @@ class App extends sugoi.BaseApp {
var tpl = loadTemplate(tpl);
var html = tpl.execute(ctx);
#if php
if ( html.substr(0, 4) == "null") html = html.substr(4);
if (html.substr(0, 4) == "null")
html = html.substr(4);
#end
return html;
}
}
+133 -127
View File
@@ -1,4 +1,5 @@
package controller;
import db.UserContract;
import sugoi.form.elements.Checkbox;
import sugoi.form.elements.Selectbox;
@@ -6,19 +7,20 @@ import sugoi.form.Form;
import sugoi.form.elements.StringInput;
import Common;
import datetime.DateTime;
using tools.ObjectListTool;
using tools.DateTool;
import service.OrderService;
class ContractAdmin extends Controller
{
public function new()
{
class ContractAdmin extends Controller {
public function new() {
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"];
App.log("first message");
}
public function sendNav(c) {
@@ -33,7 +35,6 @@ class ContractAdmin extends Controller
*/
@tpl("contractadmin/default.mtt")
function doDefault(?args:{old:Bool}) {
view.nav.push("default");
var now = Date.now();
@@ -48,7 +49,8 @@ class ContractAdmin extends Controller
// filter if current user is not manager
if (!app.user.isAmapManager()) {
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);
}*/
view.multidistribs = multidistribs;
} else {
view.multidistribs = [];
}
@@ -79,14 +80,18 @@ class ContractAdmin extends Controller
view.nav.push("products");
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;
// checks
if (app.user.amap.hasShopMode() && !app.user.amap.hasTaxonomy()) {
for (p in contract.getProducts(false)) {
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;
}
}
@@ -94,7 +99,6 @@ class ContractAdmin extends Controller
// batch enable / disable products
if (args != null) {
if (args.disable != null) {
var pids = Lambda.array(Lambda.map(args.disable.split("|"), function(x) return Std.parseInt(x)));
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)));
service.ProductService.batchEnableProducts(pids);
}
}
// generate a token
checkToken();
}
/**
* - hidden page -
* 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.Checkbox("delete", t._("Delete existing products (all orders will be deleted!)")));
if (form.checkToken()) {
if (form.getValueOf("delete") == "1") {
for (p in contract.getProducts()) {
p.lock();
@@ -145,11 +146,8 @@ class ContractAdmin extends Controller
}
throw Ok("/contractAdmin/products/" + contract.id, t._("Products copied from ") + source.name);
}
view.form = form;
}
@@ -159,7 +157,6 @@ class ContractAdmin extends Controller
*/
@tpl('contractadmin/calendar.mtt')
public function doCalendar() {
var contracts = db.Contract.getActiveContracts(app.user.amap, true, false);
// 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});
cal.set(k, v);
}
}
}
}
var n = Date.now();
view.now = new Date(n.getFullYear(), n.getMonth(), n.getDate(), 0, 0, 0).getTime();
view.calendar = Calendar.mapToArray(cal);
}
/**
@@ -222,16 +214,13 @@ class ContractAdmin extends Controller
*/
@tpl('contractadmin/ordersByTimeFrame.mtt')
function doOrdersByTimeFrame(?from:Date, ?to:Date /*, ?place:db.Place*/) {
if (from == null) {
var f = new sugoi.form.Form("listBydate", null, sugoi.form.Form.FormMethod.GET);
var now = DateTime.now();
var from = now.snap(Month(Down)).getDate();
var to = now.snap(Month(Up)).add(Day(-1)).getDate();
var el = new sugoi.form.elements.DatePicker("from", t._("Start date"), from, true);
el.format = 'LL';
f.addElement(el);
@@ -248,32 +237,33 @@ class ContractAdmin extends Controller
app.setTemplate("form.mtt");
if (f.checkToken()) {
var url = '/contractAdmin/ordersByTimeFrame/' + f.getValueOf("from").toString().substr(0, 10) +"/"+f.getValueOf("to").toString().substr(0, 10);
var url = '/contractAdmin/ordersByTimeFrame/' + f.getValueOf("from").toString().substr(0, 10) + "/"
+ f.getValueOf("to").toString().substr(0, 10);
// var p = f.getValueOf("placeId");
// if (p != null) url += "/"+p;
throw Redirect(url);
}
return;
} else {
var d1 = tools.DateTool.setHourMinute(from, 0, 0);
var d2 = tools.DateTool.setHourMinute(to, 23, 59);
var contracts = app.user.amap.getActiveContracts(true);
var cconst = [];
var cvar = [];
for (c in contracts) {
if (c.type == db.Contract.TYPE_CONSTORDERS) cconst.push(c.id);
if (c.type == db.Contract.TYPE_VARORDER) cvar.push(c.id);
if (c.type == db.Contract.TYPE_CONSTORDERS)
cconst.push(c.id);
if (c.type == db.Contract.TYPE_VARORDER)
cvar.push(c.id);
}
// distribs
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);
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
var varorders = db.UserContract.manager.search($distributionId in vdistribs.getIds(), {orderBy: userId});
@@ -293,11 +283,7 @@ class ContractAdmin extends Controller
view.from = from;
view.to = to;
view.ctotal = app.params.exists("ctotal");
}
}
/**
@@ -308,7 +294,6 @@ class ContractAdmin extends Controller
@tpl('contractadmin/ordersByDate.mtt')
function doOrdersByDate(?date:Date, ?place:db.Place) {
if (date == null) {
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);
el.format = 'LL';
@@ -324,32 +309,33 @@ class ContractAdmin extends Controller
app.setTemplate("form.mtt");
if (f.checkToken()) {
var url = '/contractAdmin/ordersByDate/' + f.getValueOf("date").toString().substr(0, 10);
var p = f.getValueOf("placeId");
if (p != null) url += "/"+p;
if (p != null)
url += "/" + p;
throw Redirect(url);
}
return;
} else {
var d1 = date.setHourMinute(0, 0);
var d2 = date.setHourMinute(23, 59);
var contracts = app.user.amap.getActiveContracts(true);
var cconst = [];
var cvar = [];
for (c in contracts) {
if (c.type == db.Contract.TYPE_CONSTORDERS) cconst.push(c.id);
if (c.type == db.Contract.TYPE_VARORDER) cvar.push(c.id);
if (c.type == db.Contract.TYPE_CONSTORDERS)
cconst.push(c.id);
if (c.type == db.Contract.TYPE_VARORDER)
cvar.push(c.id);
}
// distribs
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);
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
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
*/
@tpl('contractadmin/vendorsByDate.mtt')
function doVendorsByDate(date:Date, place:db.Place) {
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 contracts = app.user.amap.getActiveContracts(true);
@@ -387,8 +371,8 @@ class ContractAdmin extends Controller
// distribs for both types in active contracts
var distribs = db.Distribution.manager.search(($contractId in cids) && $date >= d1 && $date <= d2 && $place == place, false);
if ( distribs.length == 0 ) throw Error("/contractAdmin/ordersByDate", t._("There is no delivery at this date"));
if (distribs.length == 0)
throw Error("/contractAdmin/ordersByDate", t._("There is no delivery at this date"));
var out = new Map<Int, Dynamic>(); // key : vendor id
@@ -399,10 +383,8 @@ class ContractAdmin extends Controller
if (o == null) {
out.set(vid, {contract: d.contract, distrib: d, orders: service.ReportService.getOrdersByProduct(d)});
} else {
// add orders with existing ones
for (x in service.ReportService.getOrdersByProduct(d)) {
// find record in existing orders
var f:Dynamic = Lambda.find(o.orders, function(a) return a.pid == x.pid);
if (f == null) {
@@ -422,13 +404,11 @@ class ContractAdmin extends Controller
view.date = date;
}
/**
* Global view on orders, producer view
*/
@tpl('contractadmin/vendorsByTimeFrame.mtt')
function doVendorsByTimeFrame(from:Date, to:Date) {
var d1 = tools.DateTool.setHourMinute(from, 0, 0);
var d2 = tools.DateTool.setHourMinute(to, 23, 59);
var contracts = app.user.amap.getActiveContracts(true);
@@ -436,7 +416,8 @@ class ContractAdmin extends Controller
// distribs for both types in active contracts
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
@@ -447,10 +428,8 @@ class ContractAdmin extends Controller
if (o == null) {
out.set(vid, {contract: d.contract, distrib: d, orders: service.ReportService.getOrdersByProduct(d)});
} else {
// add orders with existing ones
for (x in service.ReportService.getOrdersByProduct(d)) {
// find record in existing orders
var f:OrderByProduct = Lambda.find(o.orders, function(a:OrderByProduct) return a.pid == x.pid);
if (f == null) {
@@ -476,11 +455,28 @@ class ContractAdmin extends Controller
var orders = [];
for (x in out) {
// empty line
orders.push({"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});
orders.push({
"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) {
if(o.vat==null) o.vat = 0;
if (o.vat == null)
o.vat = 0;
orders.push({
"quantity": view.formatNum(o.quantity),
"pname": o.pname,
@@ -506,9 +502,9 @@ class ContractAdmin extends Controller
});
totalTTC = 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);
return;
}
@@ -517,7 +513,6 @@ class ContractAdmin extends Controller
view.to = to;
}
/**
* Overview of orders for this contract in backoffice
*/
@@ -527,7 +522,8 @@ class ContractAdmin extends Controller
sendNav(contract);
// 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) {
throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
}
@@ -544,7 +540,6 @@ class ContractAdmin extends Controller
} else {
throw Ok("/contractAdmin/orders/" + contract.id, t._("The order has been deleted."));
}
}
var d = null;
@@ -556,7 +551,6 @@ class ContractAdmin extends Controller
var orders = db.UserContract.getOrders(contract, d, app.params.exists("csv"));
if (!app.params.exists("csv")) {
// show orders on disabled products
var disabledProducts = 0;
for (o in orders) {
@@ -569,18 +563,16 @@ class ContractAdmin extends Controller
view.disabledProducts = disabledProducts;
view.orders = orders;
}
}
/**
* hidden feature : updates orders by setting current product price.
*/
function doUpdatePrices(contract:db.Contract, args:{?d:db.Distribution}) {
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) {
throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
}
@@ -597,7 +589,6 @@ class ContractAdmin extends Controller
o.feesRate = contract.percentageValue;
}
o.update();
}
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")
function doDuplicate(contract:db.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 + "'";
var form = new Form("duplicate");
@@ -619,7 +610,6 @@ class ContractAdmin extends Controller
form.addElement(new Checkbox("copyDeliveries", t._("Copy deliveries"), true));
if (form.checkToken()) {
var nc = new db.Contract();
nc.name = form.getValueOf("name");
nc.startDate = contract.startDate;
@@ -641,7 +631,6 @@ class ContractAdmin extends Controller
ua.giveRight(ContractAdmin(nc.id));
}
if (form.getValueOf("copyProducts") == true) {
var prods = contract.getProducts();
for (source_p in prods) {
@@ -695,27 +684,27 @@ class ContractAdmin extends Controller
view.form = form;
}
/**
* Orders grouped by product
*/
@tpl("contractadmin/ordersByProduct.mtt")
function doOrdersByProduct(contract:db.Contract, args:{?d:db.Distribution}) {
sendNav(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 ) throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
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)
throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
var d = args != null ? args.d : null;
if (d == null) 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."));
if (d == null)
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"));
view.orders = orders;
view.distribution = d;
view.c = contract;
}
/**
@@ -723,17 +712,21 @@ class ContractAdmin extends Controller
*/
@tpl("contractadmin/ordersByProductList.mtt")
function doOrdersByProductList(contract:db.Contract, args:{?d:db.Distribution}) {
sendNav(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 ) throw Redirect("/contractAdmin/selectDistrib/" + contract.id);
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)
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.group = contract.amap;
var d = args != null ? args.d : null;
if (d == null) d = contract.getDistribs(false).first();
if (d == null) throw t._("No delivery in this contract");
if (d == null)
d = contract.getDistribs(false).first();
if (d == null)
throw t._("No delivery in this contract");
var orders = service.ReportService.getOrdersByProduct(d, false);
view.orders = orders;
@@ -747,18 +740,20 @@ class ContractAdmin extends Controller
view.nav.push("distributions");
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;
if (args != null && args.old) {
// display also old deliveries
view.deliveries = contract.getDistribs(false);
} 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);
}
/**
@@ -769,16 +764,19 @@ class ContractAdmin extends Controller
view.nav.push("distributions");
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 userCount = new Map<Int, Int>();
var suscribers = contract.getUsers();
for( u in suscribers) userCount[u.id] = 0;
for (u in suscribers)
userCount[u.id] = 0;
// populate
var increment = function(user:db.User) {
if(user==null) return;
if (user == null)
return;
var x = userCount[user.id];
if (x == null) {
userCount[user.id] = 1;
@@ -802,7 +800,6 @@ class ContractAdmin extends Controller
} else {
out2.push({user: db.User.manager.get(k), count: userCount[k]});
}
}
var num = (distribs.length * contract.distributorNum) / suscribers.length;
@@ -821,18 +818,20 @@ class ContractAdmin extends Controller
view.nav.push("view");
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;
}
@tpl("contractadmin/stats.mtt")
function doStats(contract:db.Contract, ?args:{stat:Int}) {
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;
if (args == null) args = { stat:0 };
if (args == null)
args = {stat: 0};
view.stat = args.stat;
var pids = contract.getProducts().map(function(x) return x.id);
switch (args.stat) {
@@ -842,7 +841,10 @@ class ContractAdmin extends Controller
if (pids.length == 0) {
view.anciennete = new List();
} 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:
@@ -851,7 +853,10 @@ class ContractAdmin extends Controller
var total = 0;
var totalPrice = 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) {
total += r.quantity;
totalPrice += r.price * r.quantity;
@@ -861,32 +866,29 @@ class ContractAdmin extends Controller
}
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.totalQuantity = total;
view.totalPrice = totalPrice;
}
}
/**
* Efface une commande
* @param uc
*/
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.delete();
throw Ok('/contractAdmin/orders/' + uc.product.contract.id, t._("The contract has been canceled"));
}
@tpl("contractadmin/selectDistrib.mtt")
function doSelectDistrib(c:db.Contract, ?args:{old:Bool}) {
view.nav.push("orders");
@@ -898,7 +900,6 @@ class ContractAdmin extends Controller
} else {
view.distributions = c.getDistribs(true);
}
}
/**
@@ -909,8 +910,10 @@ class ContractAdmin extends Controller
view.nav.push("orders");
sendNav(c);
if (!app.user.canManageContract(c)) 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"));
if (!app.user.canManageContract(c))
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.u = user;
@@ -918,11 +921,8 @@ class ContractAdmin extends Controller
// need to select a distribution for varying orders contracts
if (c.type == db.Contract.TYPE_VARORDER && args.d == null) {
throw Redirect("/contractAdmin/orders/" + c.id);
} else {
// members of the group
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);
}
if (order != null) ua.order = order;
if (order != null)
ua.order = order;
userOrders.push(ua);
}
// form check
if (checkToken()) {
// it's a new order, the user has been defined in the form.
if (user == null) {
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");
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
@@ -967,11 +968,11 @@ class ContractAdmin extends Controller
for (k in app.params.keys()) {
var param = app.params.get(k);
if (k.substr(0, "product".length) == "product") {
// trouve le produit dans userOrders
var pid = Std.parseInt(k.substr("product".length));
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 ?
var user2:db.User = null;
@@ -982,8 +983,10 @@ class ContractAdmin extends Controller
var user = app.params.get("user2");
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 (user.id == user2.id) throw t._("Both selected accounts must be different ones");
if (!user2.isMemberOf(app.user.amap))
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";
}
@@ -996,17 +999,21 @@ class ContractAdmin extends Controller
} else {
q = Std.parseInt(param);
}
if(q==null) continue; //ignore bad qt input
if (q == null)
continue; // ignore bad qt input
// record order
if (uo.order != null) {
// existing record
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 {
// new record
var o = OrderService.make(user, q, uo.product, distrib == null ? null : distrib.id, (app.params.get("paid" + pid) == "1"), user2, invert);
if (o != null) orders.push(o);
var o = OrderService.make(user, q, uo.product, distrib == null ? null : distrib.id, (app.params.get("paid" + pid) == "1"), user2,
invert);
if (o != null)
orders.push(o);
}
}
}
@@ -1023,5 +1030,4 @@ class ContractAdmin extends Controller
view.userOrders = userOrders;
}
}
}
+71 -57
View File
@@ -1,18 +1,15 @@
package controller;
import sugoi.db.Cache;
import sugoi.Web;
import sugoi.mail.Mail;
import Common;
using Lambda;
using tools.DateTool;
class Cron extends Controller
{
public function doDefault()
{
}
class Cron extends Controller {
public function doDefault() {}
/**
* CLI only en prod
@@ -23,7 +20,6 @@ class Cron extends Controller
} else if (App.config.DEBUG) {
return true;
} else {
if (Web.isModNeko) {
Sys.print("only CLI.");
return false;
@@ -34,15 +30,14 @@ class Cron extends Controller
}
public function doMinute() {
print("Cron.doMinute is called");
if (!canRun()) return;
if (!canRun())
return;
app.event(MinutelyCron);
sendEmailsfromBuffer();
}
/**
@@ -51,7 +46,6 @@ class Cron extends Controller
* this function can be locally tested with `neko index.n cron/hour > cron.log`
*/
public function doHour() {
app.event(HourlyCron);
distribNotif(4, db.User.UserFlags.HasEmailNotif4h); // 4h before
@@ -62,9 +56,9 @@ class Cron extends Controller
// sendOrdersByProductWhenOrdersClose();
}
public function doDaily() {
if (!canRun()) return;
if (!canRun())
return;
app.event(DailyCron);
@@ -78,7 +72,8 @@ class Cron extends Controller
var report = new StringBuf();
report.add("<h1>" + App.config.NAME + " : ERRORS</h1>");
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();
@@ -89,11 +84,11 @@ class Cron extends Controller
App.sendMail(m);
}
// 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 Poulet Exemple" && $startDate < DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 7));
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 Poulet Exemple"
&& $startDate < DateTools.delta(Date.now(), -1000.0 * 60 * 60 * 24 * 7));
// Old Messages cleaning
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.update();
}*/
}
/**
@@ -117,7 +110,6 @@ class Cron extends Controller
* @param flag
*/
function distribNotif(hour:Int, flag:db.User.UserFlags) {
// 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
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");
// 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
/*while (true) {
@@ -170,25 +163,30 @@ class Cron extends Controller
}
// toutes les distribs trouvées ont deja été traitées
if (distribs.length == 0) return;
if (distribs.length == 0)
return;
// 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);
// We have now the distribs we want to notify about.
var distribsByContractId = new Map<Int, db.Distribution>();
for (d in distribs) {
if (d == null || d.contract==null) continue;
if (d == null || d.contract == null)
continue;
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
var orders = [];
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
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) {
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.products.push(o);
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
if (o.user2 != null) {
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.products.push(o);
users.set(o.user2.id + "-" + o.product.contract.amap.id, x);
@@ -226,18 +235,25 @@ class Cron extends Controller
for (k in users.keys()) {
var x = users.get(k);
var total = 0.0;
for( o in x.products) total += o.quantity;
if(total==0.0) users.remove(k);
for (o in x.products)
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
if ( db.User.UserFlags.HasEmailNotifOuverture == flag )
{
if (db.User.UserFlags.HasEmailNotifOuverture == flag) {
for (d in distribs) {
var memberList = d.contract.amap.getMembers();
for (u in memberList) {
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.vendors.push(d.contract.vendor);
users.set(u.id + "-" + d.contract.amap.id, x);
@@ -247,16 +263,13 @@ class Cron extends Controller
}
for (u in users) {
if (u.user.flags.has(flag)) {
if (u.user.email != null) {
var group = u.distrib.contract.amap;
this.t = sugoi.i18n.Locale.init(u.user.lang); // switch to the user language
var text;
if ( db.User.UserFlags.HasEmailNotifOuverture == flag )
{
if (db.User.UserFlags.HasEmailNotifOuverture == flag) {
// order opening notif
text = t._("Opening of orders for the delivery of <b>::date::</b>", {date: view.hDate(u.distrib.date)});
text += "<br/>";
@@ -266,11 +279,11 @@ class Cron extends Controller
text += "<li>" + v + "</li>";
}
text += "</ul>";
} else {
// Distribution notif to the users
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>";
for (p in u.products) {
text += "<li>" + p.quantity + " x " + p.product.getName();
@@ -294,29 +307,28 @@ class Cron extends Controller
try {
var m = new Mail();
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());
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.setHtmlBody(app.processTemplate("mail/message.mtt", {text: text, group: group}));
App.sendMail(m, u.distrib.contract.amap);
} catch (e:Dynamic) {
app.logError(e); // email could be invalid
}
}
}
}
}
/**
* Check if there is a multi-distrib to validate.
*
* Autovalidate it after 10 days
*/
function distribValidationNotif() {
var now = Date.now();
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>");
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);
}
@@ -383,12 +396,12 @@ class Cron extends Controller
var html = t._("<p>Reminder: you have a delivery to validate.</p>");
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);
}
/*
* Autovalidate unvalidated distributions after 10 days
*/
@@ -408,17 +421,18 @@ class Cron extends Controller
print(d.toString());
service.PaymentService.validateDistribution(d);
}
// email
var ds = tools.ObjectListTool.deduplicateDistribsByKey(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 = 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);
}
}
/**
@@ -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")
*/
function sendEmailsfromBuffer() {
App.log("Send Emails from Buffer");
print("<h3>Send Emails from Buffer</h3>");
// send
for (e in sugoi.db.BufferedMail.manager.search($sdate == null, {limit: 50, orderBy: -cdate}, false)) {
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}');
e.finallySend();
Sys.sleep(0.1);
@@ -459,7 +476,6 @@ class Cron extends Controller
* Email product report when orders close
**/
function sendOrdersByProductWhenOrdersClose() {
var range = tools.DateTool.getLastHourRange();
// 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/>');
@@ -467,10 +483,8 @@ class Cron extends Controller
for (d in db.Distribution.manager.search($orderEndDate >= range.from && $orderEndDate < range.to, false)) {
service.OrderService.sendOrdersByProductReport(d);
}
}
function print(text) {
Sys.println(text + "<br/>");
}
+59 -38
View File
@@ -1,22 +1,20 @@
package controller;
import db.Message;
import db.UserContract;
import sugoi.form.ListData;
import sugoi.form.elements.*;
import sugoi.form.Form;
class Messages extends Controller
{
public function new()
{
class Messages extends Controller {
public function new() {
super();
if (!app.user.canAccessMessages()) throw Redirect("/");
if (!app.user.canAccessMessages())
throw Redirect("/");
}
@tpl("messages/default.mtt")
function doDefault() {
var form = new Form("msg");
var senderName = "";
@@ -25,7 +23,6 @@ class Messages extends Controller
if (App.current.session.data.whichUser == 1 && app.user.email2 != null) {
senderMail = app.user.email2;
senderName = app.user.firstName2 + " " + app.user.lastName2;
} else {
senderMail = app.user.email;
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;'"));
if (form.checkToken()) {
var listId = form.getElement("list").value;
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 = [];
for (d in dest) {
if (d.email != null) mails.push(d.email);
if (d.email2 != null) mails.push(d.email2);
if (d.email != null)
mails.push(d.email);
if (d.email2 != null)
mails.push(d.email2);
}
// send mail confirmation link
var e = new sugoi.mail.Mail();
e.setSubject(form.getValueOf("subject"));
for ( x in mails) e.addRecipient(x);
e.setSender(App.config.get("default_email"));
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 )
// e.setHeader("Sender", App.config.get("default_email"));
var text:String = form.getValueOf("text");
var html = app.processTemplate("mail/message.mtt", {text: text, group: app.user.amap, list: getListName(listId)});
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
var lm = new db.Message();
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.date = Date.now();
lm.body = e.getHtmlBody();
if (listId != null) lm.recipientListId = listId;
if (listId != null)
lm.recipientListId = listId;
lm.sender = app.user;
lm.insert();
throw Ok("/messages", t._("The message has been sent"));
}
@@ -83,15 +113,15 @@ class Messages extends Controller
if (app.user.isAmapManager()) {
view.sentMessages = Message.manager.search($amap == app.user.amap && $recipientListId != null, {orderBy: -date, limit: 20}, false);
} 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")
public function doMessage(msg:Message) {
if (!app.user.isAmapManager() && msg.sender.id != app.user.id) throw Error("/", t._("Non authorized access"));
if (!app.user.isAmapManager() && msg.sender.id != app.user.id)
throw Error("/", t._("Non authorized access"));
view.list = getListName(msg.recipientListId);
view.msg = msg;
@@ -106,7 +136,6 @@ class Messages extends Controller
}*/
view.status = s;
}
function getLists():FormData<String> {
@@ -117,8 +146,8 @@ class Messages extends Controller
out.push({value: '3', label: t._("TEST: me + spouse")});
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);
for (c in contracts) {
@@ -126,7 +155,6 @@ class Messages extends Controller
out.push({value: 'c' + c.id, label: label});
}
return out;
}
/**
@@ -137,11 +165,11 @@ class Messages extends Controller
var l = getLists();
for (ll in l) {
if (ll.value == listId) return ll.label;
if (ll.value == listId)
return ll.label;
}
return null;
}
function getSelection(listId:String) {
@@ -153,7 +181,6 @@ class Messages extends Controller
var pids = Lambda.map(pids, function(x) return x.id);
var up = db.UserContract.manager.search($productId in pids, false);
var users = [];
for (order in up) {
if (!Lambda.has(users, order.user)) {
@@ -164,7 +191,6 @@ class Messages extends Controller
}
}
return users;
} else {
var out = [];
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
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 (!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;
}
}
}