#lang scheme/base
(require mzlib/etc
scheme/class
scheme/contract
scheme/match
srfi/19/time
(planet untyped/unlib:3/list)
"../snooze.ss"
"attribute.ss"
"cache.ss"
"delta.ss"
"entity.ss"
"transaction.ss")
(define audit-frame%
(class delta-api%
(inherit id->entity
entity->id
id->attribute
attribute->id
make-insert-delta
make-update-delta
make-delete-delta)
(inherit-field snooze)
(init-field trail)
(field [transaction #f])
(field [changes-made? #f])
(super-new)
(define/public (get-transaction)
transaction)
(define/public (on-transaction-start)
(set! transaction (send snooze save! (make-audit-transaction (current-time time-utc)))))
(define/public (on-transaction-end metadata-struct)
(cond [(and metadata-struct changes-made?)
(send snooze save! metadata-struct)]
[(not changes-made?)
(send snooze delete! transaction)]))
(define/public (audit-insert! struct)
(define delta (make-insert-delta transaction (struct-guid struct)))
(send snooze save! delta)
(set! changes-made? #t))
(define/public (audit-update! new)
(define id (struct-id new))
(define entity (struct-entity new))
(define old (send snooze find-by-id entity id))
(define revision (struct-revision old))
(for-each (lambda (attr old-value new-value)
(unless (equal? old-value new-value)
(let* ( [attr-id (attribute->id attr)]
[attr-type (attribute-type attr)]
[delta (make-update-delta transaction (struct-guid new) revision attr old-value)])
(send snooze save! delta)
(set! changes-made? #t))))
(cddr (entity-attributes entity))
(cddr (struct-attributes old))
(cddr (struct-attributes new))))
(define/public (audit-delete! struct)
(define id (struct-id struct))
(define revision (struct-revision struct))
(define entity (struct-entity struct))
(for-each (lambda (attr value)
(define attr-id (attribute->id attr))
(define attr-type (attribute-type attr))
(define delta (make-delete-delta transaction (struct-guid struct) revision attr value))
(send snooze save! delta)
(set! changes-made? #t))
(cddr (entity-attributes entity))
(cddr (struct-attributes struct))))
(inspect #f)))
(provide audit-frame%)