~iferca/yape/trunk

« back to all changes in this revision

Viewing changes to addins/tasks/taskstorage.py

  • Committer: Israel Fernández Cabrera
  • Date: 2008-10-03 21:12:17 UTC
  • Revision ID: iferca@gmail.com-20081003211217-uu1df2ucq3wd67nd
YaPe project moved to the new YaPe project structure. Old one will work fine but it was not suitable for the next development phases

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python
2
 
# -*- coding: UTF-8 -*-
3
 
 
4
 
__license__ = """
5
 
Copyright 2008 %USERNAME% <%EMAIL%>
6
 
   
7
 
This program is free software; you can redistribute it and/or modify it
8
 
under the terms of the GNU General Public License as published by the Free
9
 
Software Foundation; either version 2 of the License, or (at your option)
10
 
any later version.
11
 
"""
12
 
 
13
 
import os
14
 
import time
15
 
import datetime
16
 
from pysqlite2 import dbapi2 as sqlite
17
 
from project.projectmanager import ProjectManager
18
 
 
19
 
class Task(object):
20
 
    """
21
 
    Represent a YaPe's task
22
 
    """
23
 
    def __init__(self, id=None, name="", description="", priority="0", start_date=datetime.date.today(), due_date=datetime.date.today(), started_date=None, end_date=None):
24
 
        """
25
 
        If no id is provided on construction a random id is generated
26
 
        Argument priority should be a string in ("0", "1", "2", "3") for ("low", "med", "bug", "high")
27
 
        
28
 
        raises: ValueError if priority receive a wrong value
29
 
        """
30
 
        self.tid = id
31
 
        if not id:
32
 
            self.tid = str(time.time())
33
 
        self.name = name
34
 
        self.description = description
35
 
        if str(priority) not in ("0", "1", "2", "3"):
36
 
            raise ValueError("Wrong priority value. Expected '0', '1', '2' or '3' and got: %s" % priority)
37
 
        self.priority = str(priority)
38
 
        if start_date and not isinstance(start_date, datetime.date):
39
 
            raise TypeError("Incorrect type for start_date argument while constructing a Task object")
40
 
        self.startDate = start_date
41
 
        if due_date and not isinstance(due_date, datetime.date):
42
 
            raise TypeError("Incorrect type for due_date argument while constructing a Task object")
43
 
        self.dueDate = due_date
44
 
        if started_date and not isinstance(started_date, datetime.date):
45
 
            raise TypeError("Incorrect type for started_date argument while constructing a Task object")
46
 
        self.startedDate = started_date
47
 
        if end_date and not isinstance(end_date, datetime.date):
48
 
            raise TypeError("Incorrect type for end_date argument while constructing a Task object")
49
 
        self.endDate = end_date
50
 
 
51
 
    def status(self):
52
 
        result = "Not started"
53
 
        today = datetime.date.today()
54
 
        if self.startedDate and not self.endDate:
55
 
            result = "In progress"
56
 
        elif self.endDate:
57
 
            result = "Done"
58
 
        return result
59
 
        
60
 
        return result
61
 
 
62
 
    def __getFormattedDate(self, date):
63
 
        return date.strftime("%a. %B %d, %Y")
64
 
 
65
 
    def isDone(self):
66
 
        return self.endDate != None
67
 
 
68
 
    def markFinished(self, finished, date=None):
69
 
        if finished:
70
 
            if date:
71
 
                self.endDate = date
72
 
            else:
73
 
                self.endDate = datetime.date.today()
74
 
        else:
75
 
            self.endDate = None
76
 
 
77
 
    def icon(self):
78
 
        if self.priority == "0":
79
 
            return "task-generic"
80
 
        elif self.priority == "1":
81
 
            return "task-med"
82
 
        elif self.priority == "2":
83
 
            return "task-bug"
84
 
        return "task-important"
85
 
 
86
 
    def __str__(self):
87
 
        return "%s, %s, %s, %s, %s, %s, %s, %s" % (self.tid, self.name, self.description, self.priority, 
88
 
                 self.startDate, self.dueDate, self.startedDate, self.endDate)
89
 
 
90
 
    def remove(self, id):
91
 
        ts = TaskStorage()
92
 
        ts.remove(id)
93
 
 
94
 
    def save(self):
95
 
        if len(self.name) == 0:
96
 
            raise ValueError("Can't save a task without a name")
97
 
        ts = TaskStorage()
98
 
        ts.write(self.tid, self.name, self.description, self.priority, 
99
 
                 self.startDate, self.dueDate, self.startedDate, self.endDate)
100
 
 
101
 
    @classmethod
102
 
    def load(self, id):
103
 
        if not id:
104
 
            raise ValueError("Incorrect id: %s" % id)
105
 
        ts = TaskStorage()
106
 
        id, name, description, priority, start_date, due_date, started_date, end_date = ts.loadTask(id)
107
 
        return Task(id, name, description, priority, start_date, due_date, started_date, end_date)
108
 
 
109
 
    @classmethod
110
 
    def all(cls):
111
 
        ts = TaskStorage()
112
 
        for id, name, description, priority, start_date, due_date, started_date, end_date in ts.tasks():
113
 
            yield Task(id, name, description, priority, start_date, due_date, started_date, end_date)
114
 
 
115
 
 
116
 
class TaskStorage(object):
117
 
    def __init__(self):
118
 
        self.__pm = ProjectManager.getInstance()
119
 
        self.__openConnection()
120
 
 
121
 
    def loadTask(self, id):
122
 
        cursor = self.__getCursor()
123
 
        q = "SELECT * FROM yape_task WHERE id = ?"
124
 
        cursor.execute(q, (id,))
125
 
        row = cursor.fetchone()
126
 
        if row:
127
 
            id, name, description, priority, start_date, due_date, started_date, end_date = row
128
 
            return id, name, description, priority, self.__normalize(start_date), \
129
 
                   self.__normalize(due_date), self.__normalize(started_date), self.__normalize(end_date)
130
 
        return None
131
 
 
132
 
    def tasks(self):
133
 
        cursor = self.__getCursor()
134
 
        q = "SELECT * FROM yape_task"
135
 
        cursor.execute(q)
136
 
        rows = cursor.fetchall()
137
 
        if rows:
138
 
            for row in rows:
139
 
                id, name, description, priority, start_date, due_date, started_date, end_date = row
140
 
                yield id, name, description, priority, self.__normalize(start_date),\
141
 
                      self.__normalize(due_date), self.__normalize(started_date), self.__normalize(end_date)
142
 
 
143
 
    def remove(self, id):
144
 
        cursor = self.__getCursor()
145
 
        q = "DELETE FROM yape_task WHERE id=?"
146
 
        cursor.execute(q, (id,))
147
 
        self._connection.commit()
148
 
 
149
 
    def write(self, id, name, description, priority, start_date, due_date, started_date, end_date):
150
 
        cursor = self.__getCursor()
151
 
        if self.loadTask(id):
152
 
            q = """UPDATE yape_task SET name=?, description=?, priority=?, start_date=?, 
153
 
                due_date=?, started_date=?, end_date=? WHERE id=?"""
154
 
            cursor.execute(q, (name, description, priority, start_date, due_date, started_date, end_date, id))
155
 
        else:
156
 
            q = """INSERT INTO yape_task(id, name, description, priority, start_date, due_date, started_date, end_date)
157
 
                values(?, ?, ?, ?, ?, ?, ?, ?)"""
158
 
            cursor.execute(q, (id, name, description, priority, start_date, due_date, started_date, end_date))
159
 
        self._connection.commit()
160
 
 
161
 
    def __normalize(self, date):
162
 
        if not date: return None
163
 
        dateItems = date.split("-")
164
 
        year = int(dateItems[0])
165
 
        month = int(dateItems[1])
166
 
        day = int(dateItems[2])
167
 
        d = datetime.date(year, month, day)
168
 
        return d
169
 
 
170
 
    def __openConnection(self):
171
 
        taskDBPath = os.path.join(self.__pm.projectLocation(), "tasks.db")
172
 
        self._connection = sqlite.connect(taskDBPath)
173
 
        if not self.__schemaExists():
174
 
            self.__createSchema()
175
 
 
176
 
    def __closeConnection(self):
177
 
        self.__connection.close()
178
 
 
179
 
    def __getCursor(self):
180
 
        return self._connection.cursor()
181
 
 
182
 
    def __createSchema(self):
183
 
        try:
184
 
            schema = """
185
 
            CREATE TABLE "yape_task"(
186
 
                "id"            varchar(20)  primary key,
187
 
                "name"          varchar(100) NOT NULL UNIQUE,
188
 
                "description"   varchar(1000) NOT NULL,
189
 
                "priority"      varchar(1) NOT NULL,
190
 
                "start_date"    date NOT NULL,
191
 
                "due_date"      date NOT NULL,
192
 
                "started_date"  date NULL,
193
 
                "end_date"      date NULL
194
 
            )
195
 
            """
196
 
            cursor = self.__getCursor()
197
 
            cursor.execute(schema)
198
 
        except sqlite.OperationalError, e:
199
 
            raise TaskStorageError("Can't create schema for tasks.")
200
 
 
201
 
    def __schemaExists(self):
202
 
        try:
203
 
            cursor = self.__getCursor()
204
 
            q = "SELECT id FROM yape_task"
205
 
            cursor.execute(q)
206
 
        except sqlite.OperationalError:
207
 
            return False
208
 
        return True
209
 
 
210
 
class TaskStorageError(Exception):
211
 
    pass