Files
freeplanet/src/store/Modules/Todos.ts

375 lines
11 KiB
TypeScript
Raw Normal View History

import { ITodo, ITodosState, IParamTodo, IDrag, IProjectsState, IProject } from 'model'
import { storeBuilder } from './Store/Store'
import Api from '@api'
import { tools } from './tools'
2019-03-22 15:32:32 +01:00
import * as ApiTables from './ApiTables'
import { GlobalStore, Todos, UserStore } from '@store'
import globalroutines from './../../globalroutines/index'
import { Mutation } from 'vuex-module-decorators'
import { serv_constants } from '@src/store/Modules/serv_constants'
import { GetterTree } from 'vuex'
import objectId from '@src/js/objectId'
2019-03-04 17:28:29 +01:00
import { costanti } from '@src/store/Modules/costanti'
const nametable = 'todos'
// import _ from 'lodash'
const state: ITodosState = {
2019-03-04 17:28:29 +01:00
showtype: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED,
2019-03-04 18:48:07 +01:00
todos: {},
categories: [],
// todos_changed: 1,
reload_fromServer: 0,
testpao: 'Test',
insidePending: false,
visuLastCompleted: 10
}
const fieldtochange: string [] = ['descr', 'status', 'category', 'expiring_at', 'priority', 'id_prev', 'pos', 'enableExpiring', 'progress']
const b = storeBuilder.module<ITodosState>('Todos', state)
const stateGetter = b.state()
function getindexbycategory(category: string) {
return state.categories.indexOf(category)
}
function gettodosByCategory(category: string) {
const indcat = state.categories.indexOf(category)
if (!state.todos[indcat]) {
return []
}
return state.todos[indcat]
}
function initcat() {
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
const objtodo: ITodo = {
// _id: new Date().toISOString(), // Create NEW
_id: objectId(),
userId: UserStore.state.userId,
descr: '',
2019-03-22 18:49:38 +01:00
priority: tools.Priority.PRIORITY_NORMAL,
status: tools.Status.OPENED,
created_at: new Date(),
modify_at: new Date(),
completed_at: new Date(),
category: '',
expiring_at: tomorrow,
enableExpiring: false,
id_prev: '',
pos: 0,
modified: false,
progress: 0
}
// return this.copy(objtodo)
return objtodo
}
namespace Getters {
2019-03-28 12:58:34 +01:00
const items_dacompletare = b.read((state: ITodosState) => (cat: string): ITodo[] => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
return state.todos[indcat].filter((todo) => todo.status !== tools.Status.COMPLETED)
} else {
return []
}
2019-03-28 12:58:34 +01:00
}, 'items_dacompletare')
const todos_completati = b.read((state: ITodosState) => (cat: string): ITodo[] => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
if (state.showtype === costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED) {
return state.todos[indcat].filter((todo) => todo.status === tools.Status.COMPLETED).slice(0, state.visuLastCompleted)
} // Show only the first N completed
else if (state.showtype === costanti.ShowTypeTask.SHOW_ALL) {
return state.todos[indcat].filter((todo) => todo.completed === tools.Status.COMPLETED)
}
else {
2019-03-04 17:28:29 +01:00
return []
}
} else {
return []
}
}, 'todos_completati')
const doneTodosCount = b.read((state: ITodosState) => (cat: string): number => {
return getters.todos_completati(cat).length
}, 'doneTodosCount')
const TodosCount = b.read((state: ITodosState) => (cat: string): number => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
return state.todos[indcat].length
} else {
return 0
}
}, 'TodosCount')
const getRecordById = b.read((state: ITodosState) => (id: string, cat: string): ITodo => {
const indcat = getindexbycategory(cat)
if (state.todos) {
return state.todos[indcat].find((item) => item._id === id)
}
return null
}, 'getRecordById')
export const getters = {
2019-03-28 12:58:34 +01:00
get items_dacompletare() {
return items_dacompletare()
},
get todos_completati() {
return todos_completati()
},
get doneTodosCount() {
return doneTodosCount()
},
get TodosCount() {
return TodosCount()
},
get getRecordById() {
return getRecordById()
}
}
}
namespace Mutations {
function findIndTodoById(state: ITodosState, data: IParamTodo) {
const indcat = state.categories.indexOf(data.categorySel)
if (indcat >= 0) {
2019-03-28 12:58:34 +01:00
return tools.getIndexById(state.todos[indcat], data.id)
}
return -1
}
function createNewItem(state: ITodosState, { objtodo, atfirst, categorySel }) {
2019-03-04 18:48:07 +01:00
let indcat = state.categories.indexOf(categorySel)
if (indcat == -1) {
state.categories.push(categorySel)
indcat = state.categories.indexOf(categorySel)
}
console.log('createNewItem', objtodo, 'cat=', categorySel, 'state.todos[indcat]', state.todos[indcat])
if (state.todos[indcat] === undefined) {
state.todos[indcat] = []
state.todos[indcat].push(objtodo)
2019-03-04 18:48:07 +01:00
console.log('push state.todos[indcat]', state.todos)
return
}
if (atfirst) {
state.todos[indcat].unshift(objtodo)
}
else {
state.todos[indcat].push(objtodo)
}
console.log('state.todos[indcat]', state.todos[indcat])
}
function deletemyitem(state: ITodosState, myitem: ITodo) {
// Find record
const indcat = state.categories.indexOf(myitem.category)
const ind = findIndTodoById(state, { id: myitem._id, categorySel: myitem.category })
2019-03-22 15:32:32 +01:00
ApiTables.removeitemfromarray(state.todos[indcat], ind)
}
export const mutations = {
deletemyitem: b.commit(deletemyitem),
createNewItem: b.commit(createNewItem)
}
}
namespace Actions {
2019-03-28 12:58:34 +01:00
async function dbLoad(context, { checkPending }) {
console.log('dbLoad', nametable, checkPending, 'userid=', UserStore.state.userId)
if (UserStore.state.userId === '') {
2019-03-22 15:32:32 +01:00
return false // Login not made
}
const ris = await Api.SendReq('/todos/' + UserStore.state.userId, 'GET', null)
.then((res) => {
2019-03-22 15:32:32 +01:00
if (res.data.todos) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
state.todos = res.data.todos
state.categories = res.data.categories
} else {
state.todos = [[]]
}
state.showtype = parseInt(GlobalStore.getters.getConfigStringbyId({
id: costanti.CONFIG_ID_SHOW_TYPE_TODOS,
default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED
}), 10)
2019-03-04 17:28:29 +01:00
// console.log('ARRAY TODOS = ', state.todos)
if (process.env.DEBUG === '1') {
2019-03-28 12:58:34 +01:00
console.log('dbLoad', 'state.todos', state.todos, 'state.categories', state.categories)
}
return res
})
.catch((error) => {
2019-03-28 12:58:34 +01:00
console.log('error dbLoad', error)
UserStore.mutations.setErrorCatch(error)
return error
})
2019-02-02 20:13:06 +01:00
2019-03-22 15:32:32 +01:00
ApiTables.aftercalling(ris, checkPending, 'categories')
}
async function deleteItemtodo(context, { cat, idobj }) {
console.log('deleteItemtodo: KEY = ', idobj)
2019-03-22 20:51:42 +01:00
const myarr = gettodosByCategory(cat)
const myobjtrov = tools.getElemById(myarr, idobj)
console.log('myobjtrov', myobjtrov.descr)
if (!!myobjtrov) {
2019-03-22 20:51:42 +01:00
const myobjnext = tools.getElemPrevById(myarr, myobjtrov._id)
if (!!myobjnext) {
myobjnext.id_prev = myobjtrov.id_prev
myobjnext.modified = true
await modify(context, { myitem: myobjnext, field: 'id_prev' })
}
2019-03-22 15:32:32 +01:00
ApiTables.table_DeleteRecord(nametable, myobjtrov, idobj)
}
}
2019-03-28 12:58:34 +01:00
async function dbInsert(context, { myobj, atfirst }) {
const objtodo = initcat()
objtodo.descr = myobj.descr
objtodo.category = myobj.category
let elemtochange: ITodo = null
2019-03-22 20:51:42 +01:00
const myarr = gettodosByCategory(objtodo.category)
if (atfirst) {
console.log('INSERT AT THE TOP')
2019-03-22 20:51:42 +01:00
elemtochange = tools.getFirstList(myarr)
2019-03-22 15:32:32 +01:00
objtodo.id_prev = ApiTables.LIST_START
} else {
console.log('INSERT AT THE BOTTOM')
// INSERT AT THE BOTTOM , so GET LAST ITEM
2019-03-22 20:51:42 +01:00
const lastelem = tools.getLastListNotCompleted(nametable, objtodo.category)
2019-03-22 15:32:32 +01:00
objtodo.id_prev = (!!lastelem) ? lastelem._id : ApiTables.LIST_START
}
objtodo.modified = false
2019-03-22 20:51:42 +01:00
Todos.mutations.createNewItem({ objtodo, atfirst, categorySel: objtodo.category }) // 1) Create record in Memory
2019-03-22 20:51:42 +01:00
const id = await globalroutines(context, 'write', nametable, objtodo) // 2) Insert into the IndexedDb
let field = ''
2019-03-22 15:32:32 +01:00
if (atfirst) { // update also the last elem
if (!!elemtochange) {
elemtochange.id_prev = id
console.log('elemtochange', elemtochange)
field = 'id_prev'
// Modify the other record
await modify(context, { myitem: elemtochange, field })
}
}
// 3) send to the Server
2019-03-22 15:32:32 +01:00
return await ApiTables.Sync_SaveItem(nametable, 'POST', objtodo)
.then((ris) => {
2019-03-22 20:51:42 +01:00
// *** Check if need to be moved because of the --- Priority Ordering --- ...
const indelem = tools.getIndexById(myarr, objtodo._id)
let itemdragend
if (atfirst) {
// Check the second item, if it's different priority, then move to the first position of the priority
const secondindelem = indelem + 1
2019-03-22 20:51:42 +01:00
if (tools.isOkIndex(myarr, secondindelem)) {
const secondelem = tools.getElemByIndex(myarr, secondindelem)
2019-03-04 17:28:29 +01:00
if (secondelem.priority !== objtodo.priority) {
itemdragend = {
field: 'priority',
idelemtochange: objtodo._id,
prioritychosen: objtodo.priority,
category: objtodo.category,
atfirst
}
}
}
} else {
// get previous of the last
const prevlastindelem = indelem - 1
2019-03-22 20:51:42 +01:00
if (tools.isOkIndex(myarr, prevlastindelem)) {
const prevlastelem = tools.getElemByIndex(myarr, prevlastindelem)
2019-03-04 17:28:29 +01:00
if (prevlastelem.priority !== objtodo.priority) {
itemdragend = {
field: 'priority',
idelemtochange: objtodo._id,
prioritychosen: objtodo.priority,
category: objtodo.category,
atfirst
}
}
}
}
if (itemdragend) {
swapElems(context, itemdragend)
}
return ris
})
}
async function modify(context, { myitem, field }) {
2019-03-22 15:32:32 +01:00
return await ApiTables.table_ModifyRecord(nametable, myitem, fieldtochange)
}
async function swapElems(context, itemdragend: IDrag) {
2019-03-28 12:58:34 +01:00
console.log('TODOS swapElems', itemdragend, state.todos, state.categories)
2019-03-22 20:51:42 +01:00
const cat = itemdragend.category
const indcat = state.categories.indexOf(cat)
2019-03-22 20:51:42 +01:00
const myarr = state.todos[indcat]
2019-03-22 20:51:42 +01:00
tools.swapGeneralElem(nametable, myarr, itemdragend, fieldtochange)
}
export const actions = {
2019-03-28 12:58:34 +01:00
dbLoad: b.dispatch(dbLoad),
swapElems: b.dispatch(swapElems),
deleteItemtodo: b.dispatch(deleteItemtodo),
2019-03-28 12:58:34 +01:00
dbInsert: b.dispatch(dbInsert),
modify: b.dispatch(modify)
}
}
// Module
const TodosModule = {
get state() {
return stateGetter()
},
getters: Getters.getters,
mutations: Mutations.mutations,
actions: Actions.actions
}
export default TodosModule