Commits

Rafał Kos committed b5ca225

save info about changes on company, order and invoice
allow to view those informations on edit pages

  • Participants
  • Parent commits db007d2

Comments (0)

Files changed (10)

pytis/controllers/histories.py

+## -*- coding: utf-8 -*-
+
+from pylons import request, response, session, tmpl_context as c, url
+from pytis.lib.base import BaseController, render
+from pytis.lib.helpers import flash
+from pytis.model import meta
+from pytis.model.history import History
+import pytis.lib.helpers as h
+
+
+class HistoriesController(BaseController):
+
+    @h.auth.authorize(h.auth.is_valid_user)
+    def __before__(self):
+        pass
+
+    def view(self, id):
+        object = request.GET.get('object', '')
+        c.history = History.query.filter(History.object_id == id).filter(History.table == object).\
+                    order_by(History.created_at.desc()).all()
+
+        return render('/histories/view.phtml')

pytis/lib/database/mappers.py

 from sqlalchemy.orm.interfaces import MapperExtension
 from sqlalchemy.orm.attributes import get_history
 from pytis.model.document import Document
+from pytis.model.history import History
 
 class DocumentMapper(MapperExtension):
-    '''Get next number of document before insert'''
+    '''
+    Get next number of document before insert
+    '''
+
     def before_insert(self, mapper, connection, instance):        
         Document.obtain_number(instance)
 
 class HistoryMapper(MapperExtension):
-    '''Versioning system'''
+    '''
+    Versioning system
+    '''
+
     def after_update(self, mapper, connection, instance):
-        history = []
-
-        for column in instance.__table__.columns:
-            change = get_history(instance, column.name)
-            if change.has_changes():
-                history.append({column.name : [change.added, change.deleted]})
-        
-        raise Exception(history)
+        history = History()
+        history.save_info_about_changes(instance)

pytis/model/company.py

             raise sa.exc.SQLAlchemyError
 
 class Company(Base):
-    __tablename__ = 'company'      
+    __tablename__ = 'company'
+    __mapper_args__ = {'extension': HistoryMapper()}
 
     query = db.query_property(db.Query)
 

pytis/model/history.py

+from sqlalchemy.orm.attributes import get_history
+from meta import Base
+from pytis.model import meta
+from pytis.model.meta import db
+from pytis.model.user import User
+from sqlalchemy import types, orm
+from sqlalchemy.orm import relation
+from sqlalchemy.schema import Column
+import pytis.lib.helpers as h
+import sqlalchemy as sa
+
+class History(Base):
+    """
+    Information about changes in database on selected tables
+    """
+
+    __tablename__ = 'history'
+    query = db.query_property(db.Query)
+
+    id = Column("id", types.Integer, primary_key=True, autoincrement=True)
+    object_id = Column("object_id", types.Integer, nullable=False)
+    text = Column("text", types.Unicode(1024), nullable=False)
+    table = Column("table", types.Unicode(64), nullable=False)
+    user_id = Column("user_id", types.Integer, sa.ForeignKey('user.id'), nullable=False)
+    created_at = Column("created_at", types.TIMESTAMP, default=sa.func.current_timestamp())
+
+    user = relation(User, uselist=False, primaryjoin=
+                                user_id == User.id,
+                                lazy=False)
+
+    def save_info_about_changes(self, instance):
+        self.text = ''
+        
+        for column in instance.__table__.columns:
+            change = get_history(instance, column.name)
+            if change.has_changes() \
+                and change.deleted and change.added \
+                and unicode(change.deleted[0]) != unicode(change.added[0]):
+                self.text += column.name + ' z ' + unicode(change.deleted[0]) + ' na ' + unicode(change.added[0]) + '\n'
+
+        if self.text:
+            self.table = instance.__table__.name
+            self.object_id = instance.id
+            self.save()               
+
+    def save(self):
+
+        if self.id is None:
+            self.user_id = h.auth.user_id()
+
+        meta.Session.add(self)

pytis/model/invoice.py

 import sqlalchemy as sa
 from decimal import Decimal
 from pylons import app_globals
-from pytis.lib.database.mappers import DocumentMapper
+from pytis.lib.database.mappers import DocumentMapper, HistoryMapper
 
 YES = 1
 NO = 0
 
 class Invoice(Base, ActionObject):
     __tablename__ = 'invoice'
-    __mapper_args__ = {'extension': DocumentMapper()}
+    __mapper_args__ = {'extension': [DocumentMapper(), HistoryMapper()]}
     
     query = db.query_property(db.Query)
 

pytis/model/order.py

 import datetime
 import pytis.lib.helpers as h
 import sqlalchemy as sa
-from pytis.lib.database.mappers import DocumentMapper
+from pytis.lib.database.mappers import DocumentMapper, HistoryMapper
 from pytis.model.driver import Driver, Truck, Semitrailer
 
 from sqlalchemy.ext.declarative import synonym_for
 class Order(Base):    
     """Zlecenie transportowe"""
     __tablename__ = 'order'
-    __mapper_args__ = {'extension': DocumentMapper()}
+    __mapper_args__ = {'extension': [DocumentMapper(), HistoryMapper()]}
     
     query = db.query_property(OrderQuery)          
     

pytis/templates/companies/edit.xhtml

 			
 		$(function() {
 			$("#country-list").msDropDown();
-			$("#tabs").tabs();			
+			$("#tabs").tabs({
+                ajaxOptions: {
+                    error: function( xhr, status, index, anchor ) {
+                        $( anchor.hash ).html(
+                            "Wystąpił problem podczas ładowania strony."
+                        );
+                    }
+			    }
+            });
 		});
     </script>
 {% endblock %}
         <li><a href="#tabs-1">Kontrahent</a></li>
         <li><a href="#tabs-2">Magazyny</a></li>
 		<li><a href="#tabs-3">Obrót roczny</a></li>
+        <li><a href="{{ url(controller='histories', action='view', id=request.urlvars['id'], object='company') }}">Historia zmian</a></li>
     </ul>
 
     <!-- KONTRAHENT -->
 	<div id="tabs-3">
 		<div class="chart" id="balance_chart"></div>		
 	</div>
+
 </div>
 </div>
 

pytis/templates/histories/view.phtml

+{% if c.history|length %}
+    <table>
+        <thead>
+            <tr>
+                <th>Kto</th>
+                <th>Co</th>
+                <th>Kiedy</th>
+            </tr>
+        </thead>
+        <tbody>
+            {% for item in c.history %}
+                <tr>
+                    <td>{{ item.user.full_name }}</td>
+                    <td>{{ item.text|replace("\n", "<br />") }}</td>
+                    <td>{{ item.created_at }}</td>
+                </tr>
+            {% endfor %}
+        </tbody>
+    </table>
+{% endif %}

pytis/templates/invoices/edit.xhtml

             <li><a href="#tabs-1">Faktura</a></li>
             <li><a href="#tabs-3">Kursy walut</a></li>
             <li><a href="#tabs-2">Dodatkowe informacje</a></li>
+            <li><a href="{{ url(controller='histories', action='view', id=request.urlvars['id'], object='invoice') }}">Historia zmian</a></li>
 		</ul>
 
         <div id="tabs-1">
 	    $('#sellDate').datepicker({
 	        dateFormat: 'yy-mm-dd'
 	    });
-	    $("#tabs").tabs();		
+	    $("#tabs").tabs({
+            ajaxOptions: {
+                error: function( xhr, status, index, anchor ) {
+                    $( anchor.hash ).html(
+                        "Wystąpił problem podczas ładowania strony."
+                    );
+                }
+            }
+        });
 	  });
 	</script>
 {% endblock %}

pytis/templates/orders/edit.xhtml

         <li><a href="#tabs-1">Zlecenie</a></li>
         <li><a href="#tabs-2">Miejsca załadunku</a></li>        
         <li><a href="#tabs-3">Dodatkowe informacje</a></li>
+        <li><a href="{{ url(controller='histories', action='view', id=request.urlvars['id'], object='order') }}">Historia zmian</a></li>
     </ul>
 	{{ h.form(url(controller='orders', action='edit', id=request.urlvars['id']), method="post", id='order-form') }}
     <div id="tabs-1">
 			}).focus();
 		})            		
 		
-        var $tabs = $("#tabs").tabs();
+        var $tabs = $("#tabs").tabs({
+            ajaxOptions: {
+                error: function( xhr, status, index, anchor ) {
+                    $( anchor.hash ).html(
+                        "Wystąpił problem podczas ładowania strony."
+                    );
+                }
+            }
+        });
 		//$("select").msDropDown();    
 		
 		$('#driver-select').live('change', function(){