Skip to content

Commit 465e87d

Browse files
committed
context seems to be working
todo: tests, improvement in mode/contextcurrent
1 parent ccd2520 commit 465e87d

File tree

7 files changed

+186
-101
lines changed

7 files changed

+186
-101
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,8 @@ The parameter `autoOrManual` are allowed 3 values:
112112
* `truthy` value - resets only the automatically set context
113113
* `falsy` value - resets only the manuallySetContext
114114

115+
The parameter `untilTime` must be a valid time format:
116+
115117
|sub_cmd|description|arguments|
116118
|---|---|---|
117119
|create|create an context| `name`, `desc`|
@@ -123,5 +125,5 @@ The parameter `autoOrManual` are allowed 3 values:
123125
|set-every|sets automatic setting of a context|`contextId`, `everyStatement`|
124126
|reset|removes manually set contexts and sets the automated ones|`autoOrManual`|
125127
|current|gets the current active contexts||
126-
|set|manually set a context|`contextId`, `untilTime`|
128+
|set|manually set a context. |`contextId`, `untilTime?`|
127129
|unset|unset a manually set context||

src/businesslogic/context.ts

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ import {taskcontext} from "./../model/taskcontext";
55
import {contextcurrent, IsSetType} from "./../model/contextcurrent";
66
import {allOrNotDone as getAllOrNotDone} from "./../helpers/BusinessLogicCommon";
77
import {getDb} from "./../helpers/ModelCommon";
8+
import {isTimeValid} from "./../helpers/Extension";
89
import {sort as sortModel} from "./../model/sort";
9-
import {parse as RepeatParser} from "./../helpers/RepeatParser";
10+
import moment = require("moment");
11+
1012

1113
export function create(name, description){
1214
var db = getDb();
@@ -93,7 +95,6 @@ export function setEvery(contextId, everyStatement) {
9395
var db = getDb();
9496
try{
9597
db.run("Begin");
96-
RepeatParser(everyStatement);
9798
contextcurrent.setEvery(contextId, everyStatement);
9899
db.run("End");
99100
} catch(err){
@@ -106,13 +107,15 @@ export function reset(autoOrManual) {
106107
var db = getDb();
107108
try{
108109
db.run("Begin");
109-
contextcurrent.removeIsSetInAll();
110-
var contextsWithEvery = contextcurrent.getAllBy({}, contextcurrent.getArrayFields("*"));
111-
contextsWithEvery.filter(function(contextCurrent) {
112-
return RepeatParser(contextCurrent.every).isToday();
113-
}).forEach(function(contextsPassed) {
114-
contextcurrent.updateIsSetByContextId(contextsPassed.contextid, IsSetType.every);
115-
});
110+
contextcurrent.removeIsSetInAll(IsSetType.unset);
111+
if(typeof autoOrManual === "undefined") {
112+
contextcurrent.removeIsSetInAll();
113+
} else if(autoOrManual) {
114+
contextcurrent.removeIsSetInAll(IsSetType.auto);
115+
} else {
116+
contextcurrent.removeIsSetInAll(IsSetType.manual);
117+
}
118+
contextcurrent.automaticContextSet();
116119
db.run("End");
117120
} catch(err){
118121
db.run("Rollback");
@@ -122,20 +125,30 @@ export function reset(autoOrManual) {
122125

123126
export function currentContexts() {
124127
var db = getDb();
125-
var activeContexts = contextcurrent.getAllBy({
126-
where: ["isset", IsSetType.every]
127-
, orWhere: ["isset", IsSetType.manual]
128-
}, "*");
128+
var activeContexts;
129+
try{
130+
db.run("Begin");
131+
contextcurrent.checkManualContextSet();
132+
contextcurrent.automaticContextSet();
133+
activeContexts = contextcurrent.currentContexts();
134+
db.run("End");
135+
} catch(err){
136+
db.run("Rollback");
137+
throw err;
138+
}
129139
return activeContexts;
130140
}
131141

132142
export function set(contextId, until){
133143
contextId = parseInt(contextId);
144+
if(until && !isTimeValid(until)) {
145+
throw Error("until is not a valid time format.");
146+
}
134147
var db = getDb();
135148
try{
136149
db.run("Begin");
137-
contextcurrent.updateIsSetByContextId(contextId, IsSetType.manual);
138-
until && contextcurrent.updateUntil(contextId, until);
150+
contextcurrent.upsertIsSetByContextId(contextId, IsSetType.manual);
151+
until && contextcurrent.upsertUntil(contextId, until);
139152
db.run("End");
140153
} catch(err){
141154
db.run("Rollback");
@@ -148,8 +161,8 @@ export function unset(contextId) {
148161
var db = getDb();
149162
try{
150163
db.run("Begin");
151-
contextcurrent.updateIsSetByContextId(contextId, null);
152-
contextcurrent.updateUntil(contextId, null);
164+
contextcurrent.upsertIsSetByContextId(contextId, IsSetType.unset);
165+
contextcurrent.upsertUntil(contextId, null);
153166
db.run("End");
154167
} catch(err){
155168
db.run("Rollback");

src/commands/context.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,45 @@ command.create("move-task", function(subcmd, opts, args, cb) {
7272
.help("move task: taskId, newContextId")
7373
.aliases(["move-t"]);
7474

75+
command.create("set-every", function(subcmd, opts, args, cb) {
76+
var db = getDb();
77+
var res = contextpage.setEvery.apply(contextpage, args);
78+
console.log(res);
79+
saveDb();
80+
cb();
81+
})
82+
.help("sets automatic setting of a context");
83+
command.create("reset", function(subcmd, opts, args, cb) {
84+
var db = getDb();
85+
var res = contextpage.reset.apply(contextpage, args);
86+
console.log(res);
87+
saveDb();
88+
cb();
89+
})
90+
.help("removes manually set contexts and sets the automated ones")
91+
command.create("current", function(subcmd, opts, args, cb) {
92+
var db = getDb();
93+
var res = contextpage.currentContexts.apply(contextpage, args);
94+
console.log(res);
95+
saveDb();
96+
cb();
97+
})
98+
.help("gets the current active contexts");
99+
command.create("set", function(subcmd, opts, args, cb) {
100+
var db = getDb();
101+
var res = contextpage.set.apply(contextpage, args);
102+
console.log(res);
103+
saveDb();
104+
cb();
105+
})
106+
.help("manually set a context");
107+
command.create("unset", function(subcmd, opts, args, cb) {
108+
var db = getDb();
109+
var res = contextpage.unset.apply(contextpage, args);
110+
console.log(res);
111+
saveDb();
112+
cb();
113+
})
114+
.help("unset a manually set context");
115+
75116
export default ContextPage;

src/helpers/BusinessLogicExecutor.ts

Lines changed: 0 additions & 68 deletions
This file was deleted.

src/helpers/Extension.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
var path = require("path");
2+
import moment = require("moment");
23

34
//define function: join all paths passed with process.cwd
45
export function joinCwd(...any) {
@@ -13,3 +14,13 @@ export function createJoinResolve(...any) {
1314
return path.resolve.apply(undefined, args.concat(args2));
1415
}
1516
}
17+
18+
export function isTimeValid(time){
19+
time = time.toLowerCase().trim();
20+
return moment(time, ["h:mma", "H:mma"], true).isValid();
21+
}
22+
23+
export function parseTime(time){
24+
time = time.toLowerCase().trim();
25+
return moment(time, ["h:mma", "H:mma"], true);
26+
}

src/helpers/RepeatParser.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ class LexicalStateMachine{
6262
var lexer = this._lexer = new Lexer(function (token) {
6363
if(self._isUsingDefaultSpace && self._defaultSpaceRegex.test(token)){}
6464
else {
65-
throw new Error(`Unexpected "${token}" near "${self._lastToken}"`);
65+
throw new Error(`Unexpected "${token}" after "${self._lastToken}"`);
6666
}
6767
});
6868
this._states.map(x => pick(x, 'name', 'regex', 'cb'))
@@ -140,11 +140,12 @@ export function parse(input) {
140140

141141
return {
142142
isToday: function(){
143-
return _recur.matches(moment().format("YYYY-MM-DD"));
143+
var retVal = _recur.matches(moment().format("YYYY-MM-DD"));
144+
return retVal;
144145
} };
145146
}
146147

147-
console.log(parse("every day").isToday());
148-
console.log(parse("every Thursday").isToday());
149-
console.log(parse("every month on the 16th").isToday());
150-
console.log(parse("every monday at 12:00pm").isToday());
148+
// console.log(parse("every day").isToday());
149+
// console.log(parse("every Thursday").isToday());
150+
// console.log(parse("every month on the 16th").isToday());
151+
// console.log(parse("every monday at 12:00pm").isToday());

src/model/contextcurrent.ts

Lines changed: 94 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1-
import {BaseModel, SQLBuilder} from "./baseModel"
1+
import {BaseModel, SQLBuilder} from "./baseModel";
22
import {DBNames} from "./../helpers/ModelCommon";
3+
import {parse as RepeatParser} from "./../helpers/RepeatParser";
4+
import {parseTime} from "./../helpers/Extension";
5+
import moment = require("moment");
36

47
export const IsSetType = {
58
manual:"manual"
6-
, every: "every"
9+
, auto: "auto"
10+
, unset: "unset"
711
}
812

913
class ContextCurrent extends BaseModel{
@@ -22,21 +26,102 @@ class ContextCurrent extends BaseModel{
2226
db.run(q.toString());
2327
}
2428
setEvery(contextId, every){
25-
var sql = SQLBuilder(this.dbName).update("every", every).where("contextid", contextId).toString();
29+
RepeatParser(every);
30+
//generalize this upsert soon
31+
var sql = SQLBuilder.raw(`INSERT OR REPLACE INTO ${this.dbName} (contextid, every, issetuntil, isset)
32+
VALUES ( ${contextId}
33+
, "${every}"
34+
, (SELECT issetuntil FROM ${this.dbName} WHERE contextid = ${contextId})
35+
, (SELECT isset FROM ${this.dbName} WHERE contextid = ${contextId})
36+
);
37+
`).toString();
2638
this.db.run(sql);
2739
}
28-
removeIsSetInAll() {
29-
var sql = SQLBuilder(this.dbName).update("isset", null).toString();
30-
this.db.run(sql);
40+
removeIsSetInAll(whereIsSet?) {
41+
//if has every, remove issetuntil
42+
var sql: any = SQLBuilder(this.dbName)
43+
.update("isset", null)
44+
.update("issetuntil", null)
45+
.whereRaw("every is not null or trim(every) <> \"\" ");
46+
if(typeof whereIsSet !== "undefined") {
47+
sql.andWhere("isset", whereIsSet)
48+
}
49+
this.db.run(sql.toString());
3150
}
32-
updateIsSetByContextId(contextId, isSet) {
51+
upsertIsSetByContextId(contextId, isSet) {
52+
//generalize this upsert soon
53+
var sql = SQLBuilder.raw(`INSERT OR REPLACE INTO ${this.dbName} (contextid, isset, issetuntil, every)
54+
VALUES ( ${contextId}
55+
, "${isSet}"
56+
, (SELECT issetuntil FROM ${this.dbName} WHERE contextid = ${contextId})
57+
, (SELECT every FROM ${this.dbName} WHERE contextid = ${contextId})
58+
);
59+
`).toString();
60+
this.db.run(sql);
3361
var sql = SQLBuilder(this.dbName).update("isset", isSet).where("contextid", contextId).toString();
3462
this.db.run(sql);
3563
}
36-
updateUntil(contextId, until) {
37-
var sql = SQLBuilder(this.dbName).update("issetuntil", until).where("contextid", contextId).toString();
64+
upsertUntil(contextId, until) {
65+
//generalize this upsert soon
66+
var sql = SQLBuilder.raw(`INSERT OR REPLACE INTO ${this.dbName} (contextid, isset, every, issetuntil)
67+
VALUES ( ${contextId}
68+
, (SELECT isset FROM ${this.dbName} WHERE contextid = ${contextId})
69+
, (SELECT every FROM ${this.dbName} WHERE contextid = ${contextId})
70+
, "${until}"
71+
);
72+
`).toString();
3873
this.db.run(sql);
3974
}
75+
automaticContextSet() {
76+
77+
var sql = SQLBuilder(DBNames.contextcurrent)
78+
.whereRaw("isset is null and every is not null and trim(every) <> \"\"")
79+
80+
var contextsWithEvery = this.db.exec(sql.toString())
81+
.map(BaseModel.MapExecResult)[0] || [];
82+
83+
contextsWithEvery.filter(function(contextCurrent) {
84+
return RepeatParser(contextCurrent.every).isToday();
85+
}).forEach(function(contextsPassed) {
86+
contextcurrent.upsertIsSetByContextId(contextsPassed.contextid, IsSetType.auto);
87+
});
88+
}
89+
checkManualContextSet() {
90+
var manualSetContext = contextcurrent.getAllBy({
91+
where: ["isset", IsSetType.manual]
92+
, andWhere: ["issetuntil", "<>", ""]
93+
, whereNotNull: ["issetuntil"]
94+
}, "*");
95+
manualSetContext = manualSetContext || [];
96+
manualSetContext.filter(function(contextCurrent) {
97+
var momentTime = parseTime(contextCurrent.issetuntil);
98+
var today = moment();
99+
//make sure it is today with the time set
100+
momentTime = moment()
101+
.hours(momentTime.hours())
102+
.minutes(momentTime.minutes())
103+
.seconds(momentTime.seconds())
104+
;
105+
return today.isAfter(momentTime);
106+
})
107+
.forEach(function(contextCurrent) {
108+
contextcurrent.upsertIsSetByContextId(contextCurrent.contextid, null);
109+
contextcurrent.upsertUntil(contextCurrent.contextid, null);
110+
});
111+
}
112+
currentContexts() {
113+
var contextFields = [
114+
`context.*`
115+
];
116+
var res = SQLBuilder.select(contextFields)
117+
.from(this.dbName)
118+
.where("isset", IsSetType.auto)
119+
.orWhere("isset", IsSetType.manual)
120+
.andWhereNot("isset", IsSetType.unset)
121+
.innerJoin(DBNames.context, `${this.dbName}.contextid`, `${DBNames.context}.id`)
122+
.toString();
123+
return this.db.exec(res).map(BaseModel.MapExecResult)[0];
124+
}
40125
}
41126

42127
var contextcurrent = new ContextCurrent();

0 commit comments

Comments
 (0)