parent
5201ef922b
commit
d634042835
|
@ -1,8 +1,5 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# TODO / FIXME
|
||||
# - lever une exception lorsque nb_lines dépasse 999 (et autres compteurs)
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
|
@ -12,42 +9,83 @@ import time
|
|||
import datetime
|
||||
import hashlib
|
||||
import base64
|
||||
import json
|
||||
from smtplib import SMTP, SMTPException
|
||||
|
||||
|
||||
from calebasse.facturation.models import Invoicing
|
||||
from batches import build_batches
|
||||
from transmission_utils import build_mail
|
||||
|
||||
OUTPUT_DIRECTORY = '/var/lib/calebasse/B2/'
|
||||
DEFAULT_OUTPUT_DIRECTORY = '/var/lib/calebasse/B2'
|
||||
DEFAULT_NORME = 'CP '
|
||||
DEFAULT_TYPE_EMETTEUR = 'TE'
|
||||
DEFAULT_APPLICATION = 'TR'
|
||||
DEFAULT_CATEGORIE = '189'
|
||||
DEFAULT_STATUT = '60'
|
||||
DEFAULT_MODE_TARIF = '05'
|
||||
DEFAULT_MESSAGE = 'ENTROUVERT 0143350135 CALEBASSE 1307'
|
||||
|
||||
# B2 informations / configuration
|
||||
# from settings.py :
|
||||
# B2_TRANSMISSION = {
|
||||
# 'nom': 'CMPP FOOBAR',
|
||||
# 'numero_emetteur': '123456789',
|
||||
# 'smtp_from': 'transmission@domaine.fr',
|
||||
# ...
|
||||
# }
|
||||
|
||||
try:
|
||||
from django.conf import settings
|
||||
b2_transmission_settings = settings.B2_TRANSMISSION or {}
|
||||
except (ImportError, AttributeError):
|
||||
b2_transmission_settings = {}
|
||||
|
||||
#
|
||||
# B2 informations
|
||||
#
|
||||
NORME = 'CP '
|
||||
NORME = b2_transmission_settings.get('norme', DEFAULT_NORME)
|
||||
|
||||
TYPE_EMETTEUR = 'TE'
|
||||
NUMERO_EMETTEUR = '420788606'
|
||||
APPLICATION = 'TR'
|
||||
MESSAGE = 'ENTROUVERT 0143350135 CALEBASSE 1301'
|
||||
MESSAGE = MESSAGE + ' '*(37-len(MESSAGE))
|
||||
TYPE_EMETTEUR = b2_transmission_settings.get('type_emetteur', DEFAULT_TYPE_EMETTEUR)
|
||||
NUMERO_EMETTEUR = b2_transmission_settings.get('numero_emetteur')
|
||||
APPLICATION = b2_transmission_settings.get('application', DEFAULT_APPLICATION)
|
||||
|
||||
CATEGORIE = '189'
|
||||
STATUT = '60'
|
||||
MODE_TARIF = '05'
|
||||
NOM = 'CMPP SAINT ETIENNE'
|
||||
CATEGORIE = b2_transmission_settings.get('categorie', DEFAULT_CATEGORIE)
|
||||
STATUT = b2_transmission_settings.get('statut', DEFAULT_STATUT)
|
||||
MODE_TARIF = b2_transmission_settings.get('mode_tarif', DEFAULT_MODE_TARIF)
|
||||
|
||||
NOM = b2_transmission_settings.get('nom', '')[:40]
|
||||
NOM = NOM + ' '*(40-len(NOM))
|
||||
|
||||
#
|
||||
# mailing
|
||||
#
|
||||
B2FILES = OUTPUT_DIRECTORY + '*-mail'
|
||||
FROM = 'teletransmission@aps42.org'
|
||||
SMTP_LOGIN = 'teletransmission'
|
||||
SMTP_PASSWORD = os.environ.get('CALEBASSE_B2_SMTP_PASSWD')
|
||||
# if there is a CALEBASSE_B2_DEBUG_TO environment variable, send all B2 mails
|
||||
# to this address instead of real ones (yy.xxx@xxx.yy.rss.fr)
|
||||
DEBUG_TO = os.environ.get('CALEBASSE_B2_DEBUG_TO')
|
||||
MESSAGE = b2_transmission_settings.get('message', DEFAULT_MESSAGE)[:37]
|
||||
MESSAGE = MESSAGE + ' '*(37-len(MESSAGE))
|
||||
|
||||
# b2 output
|
||||
OUTPUT_DIRECTORY = b2_transmission_settings.get('output_directory', DEFAULT_OUTPUT_DIRECTORY)
|
||||
|
||||
# mailing
|
||||
SMTP_FROM = b2_transmission_settings.get('smtp_from')
|
||||
SMTP_HOST = b2_transmission_settings.get('smtp_host', '127.0.0.1')
|
||||
SMTP_PORT = b2_transmission_settings.get('smtp_port', 25)
|
||||
SMTP_LOGIN = b2_transmission_settings.get('smtp_login')
|
||||
SMTP_PASSWORD = b2_transmission_settings.get('smtp_password')
|
||||
SMTP_DELAY = b2_transmission_settings.get('smtp_delay')
|
||||
|
||||
# if "smtp_debug_to" setting is present, send all B2 mails to this address
|
||||
# instead of real ones (yy.xxx@xxx.yy.rss.fr) and output SMTP dialog
|
||||
DEBUG_TO = b2_transmission_settings.get('smtp_debug_to')
|
||||
|
||||
|
||||
def b2_is_configured():
|
||||
if 'nom' in b2_transmission_settings and \
|
||||
'numero_emetteur' in b2_transmission_settings and \
|
||||
'smtp_from' in b2_transmission_settings:
|
||||
return True
|
||||
return False
|
||||
|
||||
def b2_output_directory():
|
||||
if not os.path.isdir(OUTPUT_DIRECTORY):
|
||||
raise IOError('B2 output directory (%s) is not a directory' % OUTPUT_DIRECTORY)
|
||||
if not os.access(OUTPUT_DIRECTORY, os.R_OK + os.W_OK + os.X_OK):
|
||||
raise IOError('B2 output directory (%s) is not accessible (rwx)' % OUTPUT_DIRECTORY)
|
||||
return OUTPUT_DIRECTORY
|
||||
|
||||
def filler(n, car=' '):
|
||||
return car*n
|
||||
|
@ -77,7 +115,7 @@ def get_control_key(nir):
|
|||
|
||||
def write128(output_file, line):
|
||||
if len(line) != 128:
|
||||
raise RuntimeError('length of this B2 line is %d != 128 : <<%s>>' %
|
||||
raise RuntimeError('length of this B2 line is %d != 128 : "%s"' %
|
||||
(len(line), line))
|
||||
output_file.write(line)
|
||||
|
||||
|
@ -148,16 +186,32 @@ def b2(seq_id, hc, batches):
|
|||
total = sum(b.total for b in batches)
|
||||
first_batch = min(b.number for b in batches)
|
||||
|
||||
output_dir = os.path.join(b2_output_directory(), '%s' % seq_id)
|
||||
if not os.path.isdir(output_dir):
|
||||
os.mkdir(output_dir)
|
||||
|
||||
infos = {
|
||||
'seq_id': seq_id,
|
||||
'hc': u'%s' % hc,
|
||||
'hc_b2': to,
|
||||
'batches': [],
|
||||
'total': float(total)
|
||||
}
|
||||
|
||||
# B2 veut un identifiant de fichier sur 6 caractères alphanum
|
||||
hexdigest = hashlib.sha256('%s%s%s%s%s' % (seq_id, first_batch, NUMERO_EMETTEUR, to, total)).hexdigest()
|
||||
file_id = base64.encodestring(hexdigest).upper()[0:6]
|
||||
|
||||
utcnow = datetime.datetime.utcnow()
|
||||
prefix = '%s-%s-%s-%s-%s.' % (seq_id, NUMERO_EMETTEUR, to, first_batch, file_id)
|
||||
|
||||
b2_filename = os.path.join(output_dir, prefix + 'b2')
|
||||
assert not os.path.isfile(b2_filename), 'B2 file "%s" already exists' % b2_filename
|
||||
|
||||
output_file = tempfile.NamedTemporaryFile(suffix='.b2tmp',
|
||||
prefix=prefix, dir=OUTPUT_DIRECTORY, delete=False)
|
||||
prefix=prefix, dir=output_dir, delete=False)
|
||||
|
||||
nb_lines = 0
|
||||
|
||||
utcnow = datetime.datetime.utcnow()
|
||||
start_000 = '000' + TYPE_EMETTEUR + '00000' + NUMERO_EMETTEUR + \
|
||||
filler(6) + to + filler(6) + APPLICATION + \
|
||||
file_id + b2date(utcnow) + NORME + 'B2' + filler(15) + \
|
||||
|
@ -175,6 +229,14 @@ def b2(seq_id, hc, batches):
|
|||
write128(output_file, start_1)
|
||||
nb_lines += 1
|
||||
|
||||
infos['batches'].append({
|
||||
'batch': batch.number,
|
||||
'hc': u'%s' % batch.health_center,
|
||||
'total': float(batch.total),
|
||||
'number_of_invoices': batch.number_of_invoices,
|
||||
'number_of_acts': batch.number_of_acts
|
||||
})
|
||||
|
||||
for i in batch.invoices:
|
||||
nb_lines += write_invoice(output_file, i)
|
||||
|
||||
|
@ -192,8 +254,6 @@ def b2(seq_id, hc, batches):
|
|||
nb_batches += 1
|
||||
|
||||
if nb_lines > 990:
|
||||
# FIXME grouper les lots comme y fo pour que ca n'arrive jamais
|
||||
print "[FIXME] TROP DE LIGNES -- ", nb_lines
|
||||
raise
|
||||
|
||||
end_999 = '999' + TYPE_EMETTEUR + '00000' + NUMERO_EMETTEUR + \
|
||||
|
@ -208,71 +268,102 @@ def b2(seq_id, hc, batches):
|
|||
old_filename = output_file.name
|
||||
output_file.close()
|
||||
|
||||
b2_filename = os.path.join(OUTPUT_DIRECTORY, prefix + 'b2')
|
||||
b2_filename = os.path.join(output_dir, prefix + 'b2')
|
||||
os.rename(old_filename, b2_filename)
|
||||
|
||||
# create S/MIME mail
|
||||
mail_filename = build_mail(hc.large_regime.code, hc.dest_organism, b2_filename)
|
||||
fd = open(b2_filename + '-mail', 'w')
|
||||
fd.write(build_mail(hc.large_regime.code, hc.dest_organism, b2_filename))
|
||||
fd.close()
|
||||
|
||||
return b2_filename, mail_filename
|
||||
# create info file (json)
|
||||
basename = os.path.basename(b2_filename)
|
||||
infos['files'] = {
|
||||
'b2': basename,
|
||||
'self': basename + '-info',
|
||||
'mail': basename + '-mail'
|
||||
}
|
||||
fd = open(b2_filename + '-info', 'w')
|
||||
json.dump(infos, fd, sort_keys=True, indent=4, separators=(',', ': '))
|
||||
fd.close()
|
||||
|
||||
return b2_filename
|
||||
|
||||
def buildall(seq_id):
|
||||
try:
|
||||
invoicing = Invoicing.objects.filter(seq_id=seq_id)[0]
|
||||
except IndexError:
|
||||
raise RuntimeError('Facture introuvable')
|
||||
batches = build_batches(invoicing)
|
||||
for hc in batches:
|
||||
for b in batches[hc]:
|
||||
b2_filename = b2(invoicing.seq_id, hc, [b])
|
||||
|
||||
|
||||
def sendmail(mail):
|
||||
def sendmail_raw(mail):
|
||||
if DEBUG_TO:
|
||||
toaddr = DEBUG_TO
|
||||
print '(debug mode, sending to', toaddr, ')'
|
||||
else:
|
||||
toaddr = re.search('\nTo: +(.*)\n', mail, re.MULTILINE).group(1)
|
||||
fromaddr = FROM
|
||||
|
||||
smtp = SMTP('mail.aps42.org',587)
|
||||
smtp = SMTP(SMTP_HOST, SMTP_PORT)
|
||||
if DEBUG_TO:
|
||||
smtp.set_debuglevel(1)
|
||||
if SMTP_LOGIN:
|
||||
smtp.ehlo()
|
||||
if SMTP_LOGIN and SMTP_PASSWORD:
|
||||
smtp.starttls()
|
||||
smtp.ehlo()
|
||||
smtp.login(SMTP_LOGIN, SMTP_PASSWORD)
|
||||
ret = smtp.sendmail(fromaddr, toaddr, mail)
|
||||
smtp.sendmail(SMTP_FROM, toaddr, mail)
|
||||
smtp.close()
|
||||
return ret
|
||||
return toaddr, "%s:%s" % (SMTP_HOST, SMTP_PORT)
|
||||
|
||||
def sendall():
|
||||
if not SMTP_PASSWORD:
|
||||
print 'CALEBASSE_B2_SMTP_PASSWD envvar is missing...'
|
||||
return
|
||||
for mail_filename in glob.glob(B2FILES):
|
||||
print 'sending', mail_filename
|
||||
def sendmail(seq_id, oneb2=None):
|
||||
output_dir = os.path.join(b2_output_directory(), '%s' % seq_id)
|
||||
if oneb2:
|
||||
filename = os.path.join(output_dir, oneb2 + '-mail')
|
||||
if os.path.isfile(filename + '-sent'): # resent
|
||||
os.rename(filename + '-sent', filename)
|
||||
filenames = [filename]
|
||||
else:
|
||||
filenames = glob.glob(os.path.join(output_dir, '*.b2-mail'))
|
||||
for mail_filename in filenames:
|
||||
log = open(mail_filename + '.log', 'a')
|
||||
log.write('%s mail %s\n' % (datetime.datetime.now(), os.path.basename(mail_filename)))
|
||||
mail = open(mail_filename).read()
|
||||
try:
|
||||
sendmail(mail)
|
||||
to, via = sendmail_raw(mail)
|
||||
except SMTPException as e:
|
||||
print ' SMTP ERROR:', e
|
||||
log.write('%s SMTP ERROR: %s\n' % (datetime.datetime.now(), e))
|
||||
else:
|
||||
print ' sent'
|
||||
log.write('%s OK, MAIL SENT TO %s VIA %s\n' % (datetime.datetime.now(), to, via))
|
||||
os.rename(mail_filename, mail_filename + '-sent')
|
||||
time.sleep(10)
|
||||
os.utime(mail_filename + '-sent', None) # touch
|
||||
log.close()
|
||||
if SMTP_DELAY:
|
||||
time.sleep(SMTP_DELAY) # Exchange, I love you.
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "calebasse.settings")
|
||||
from calebasse.facturation.models import Invoicing
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print 'just (re)send all mails...'
|
||||
sendall()
|
||||
sys.exit(0)
|
||||
|
||||
try:
|
||||
invoicing = Invoicing.objects.filter(seq_id=sys.argv[1])[0]
|
||||
except IndexError:
|
||||
raise RuntimeError('Facture introuvable')
|
||||
print 'Facturation', invoicing.seq_id
|
||||
batches = build_batches(invoicing)
|
||||
for hc in batches:
|
||||
print 'pour', hc
|
||||
for b in batches[hc]:
|
||||
print ' lot', b
|
||||
b2_filename, mail_filename = b2(invoicing.seq_id, hc, [b])
|
||||
print ' B2 :', b2_filename
|
||||
print ' smime :', mail_filename
|
||||
sendall()
|
||||
|
||||
def get_all_infos(seq_id):
|
||||
output_dir = os.path.join(b2_output_directory(), '%s' % seq_id)
|
||||
infos = []
|
||||
for mail_filename in glob.glob(os.path.join(output_dir, '*.b2-info')):
|
||||
fd = open(mail_filename, 'r')
|
||||
info = json.load(fd)
|
||||
stats = os.stat(os.path.join(output_dir, info['files']['b2']))
|
||||
info['creation_date'] = datetime.datetime.fromtimestamp(stats.st_mtime)
|
||||
try:
|
||||
stats = os.stat(os.path.join(output_dir, info['files']['mail'] + '-sent'))
|
||||
info['mail_date'] = datetime.datetime.fromtimestamp(stats.st_mtime)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
fd = open(os.path.join(output_dir, info['files']['mail'] + '.log'), 'r')
|
||||
info['mail_log'] = fd.read()
|
||||
fd.close()
|
||||
except:
|
||||
pass
|
||||
infos.append(info)
|
||||
fd.close()
|
||||
return infos
|
||||
|
|
|
@ -1,9 +1,28 @@
|
|||
import os
|
||||
from datetime import datetime
|
||||
import time
|
||||
import email
|
||||
from glob import glob
|
||||
from gzip import GzipFile
|
||||
from StringIO import StringIO
|
||||
|
||||
from noemie_format import NOEMIE
|
||||
from b2 import b2_transmission_settings
|
||||
|
||||
DEFAULT_NOEMIE_DIRECTORY = '/var/lib/calebasse/B2/NOEMIE'
|
||||
|
||||
NOEMIE_DIRECTORY = b2_transmission_settings.get('noemie_directory', DEFAULT_NOEMIE_DIRECTORY)
|
||||
|
||||
def noemie_output_directory():
|
||||
if not os.path.isdir(NOEMIE_DIRECTORY):
|
||||
raise IOError('NOEMIE output directory (%s) is not a directory' % NOEMIE_DIRECTORY)
|
||||
if not os.access(NOEMIE_DIRECTORY, os.R_OK + os.X_OK):
|
||||
raise IOError('NOEMIE output directory (%s) is not readable (r-x)' % NOEMIE_DIRECTORY)
|
||||
return NOEMIE_DIRECTORY
|
||||
|
||||
|
||||
def noemie_try_gunzip(data):
|
||||
"gunzip data if its a gzip stream"
|
||||
"gunzip data if it is a gzip stream"
|
||||
sio = StringIO(data)
|
||||
gz = GzipFile(fileobj=sio, mode='rb')
|
||||
try:
|
||||
|
@ -19,7 +38,17 @@ def noemie_decode(data):
|
|||
entity = data[:3]
|
||||
analyzer = NOEMIE.get(entity)
|
||||
if analyzer is None:
|
||||
raise Exception('cannot analyse NOEMIE line "%s..."' % data[:32])
|
||||
split = data.split('@',1)
|
||||
if len(split) < 2:
|
||||
raw, data = data, ''
|
||||
else:
|
||||
raw, data = split
|
||||
lines.append({
|
||||
'description': 'Error: unknown entity %s' % entity,
|
||||
'segments': [],
|
||||
'raw': raw,
|
||||
})
|
||||
continue
|
||||
line = { 'description': analyzer['description'] }
|
||||
segments = []
|
||||
index = 0
|
||||
|
@ -35,13 +64,67 @@ def noemie_decode(data):
|
|||
index += anaseg['size']
|
||||
segments.append(seg)
|
||||
line['segments'] = segments
|
||||
line['data'] = data[:index]
|
||||
line['raw'] = data[:index]
|
||||
data = data[index:]
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
from pprint import pprint
|
||||
data = noemie_try_gunzip(open(sys.argv[1]).read())
|
||||
pprint(noemie_decode(data), indent=2)
|
||||
|
||||
def noemie_from_mail(name, with_data=True):
|
||||
filename = os.path.join(noemie_output_directory(), name)
|
||||
fp = open(filename, 'rb')
|
||||
try:
|
||||
mail = email.message_from_file(fp)
|
||||
except:
|
||||
fp.close()
|
||||
return None
|
||||
fp.close()
|
||||
|
||||
noemie = [part for part in mail.walk() \
|
||||
if part.get_content_type().lower() == 'application/edi-consent']
|
||||
if not noemie:
|
||||
return None
|
||||
noemie = noemie[0] # only one NOEMIE part per email
|
||||
|
||||
subject = mail.get('Subject')
|
||||
from_addr = mail.get('From')
|
||||
to_addr = mail.get('To')
|
||||
nature = noemie.get('Content-Description')
|
||||
if with_data:
|
||||
data = noemie.get_payload()
|
||||
if 'base64' == noemie.get('Content-Transfer-Encoding').lower():
|
||||
data = data.decode('base64')
|
||||
data = noemie_try_gunzip(data)
|
||||
data = noemie_decode(data)
|
||||
|
||||
filedate = datetime.fromtimestamp(os.stat(filename).st_mtime)
|
||||
try:
|
||||
date = email.Utils.parsedate(mail.get('Date', mail.get('Delivery-date')))
|
||||
if isinstance(date, tuple):
|
||||
date = datetime.fromtimestamp(time.mktime(date))
|
||||
else:
|
||||
date = filedate
|
||||
except:
|
||||
date = filedate
|
||||
|
||||
# TODO: try to get HealthCenter from from_addr
|
||||
result = {
|
||||
'name': name,
|
||||
'date': date,
|
||||
'from': from_addr,
|
||||
'to': to_addr,
|
||||
'subject': subject,
|
||||
'nature': nature,
|
||||
}
|
||||
if with_data:
|
||||
result['data'] = data
|
||||
return result
|
||||
|
||||
def noemie_mails():
|
||||
mails = []
|
||||
for filename in glob(os.path.join(noemie_output_directory(), '*')):
|
||||
mail = noemie_from_mail(os.path.basename(filename), with_data=False)
|
||||
if mail:
|
||||
mails.append(mail)
|
||||
mails.sort(key=lambda x: x['date'], reverse=True)
|
||||
return mails
|
||||
|
|
|
@ -28,7 +28,7 @@
|
|||
{% if invoicing.status == "open" %}<button id="close-invoicing">Clore cette facturation</button>{% endif %}
|
||||
{% if invoicing.status == "closed" %}<button id="validate"">Valider cette facturation</button>{% endif %}
|
||||
{% if invoicing.status == "validated" %}
|
||||
<!--<button id="teletrans-btn">Télétransmission à l'assurance maladie</button>-->
|
||||
<button onclick="window.location.href=window.location.href+'transmission/'">Télétransmission</button>
|
||||
<button onclick="window.location.href=window.location.href+'export/'">Export comptabilité</button>
|
||||
<button onclick="window.location.href=window.location.href+'download/'">Imprimer</button>
|
||||
{% endif %}
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
{% extends "facturation/base.html" %}
|
||||
{% load url from future %}
|
||||
|
||||
{% block appbar %}
|
||||
<h2>Messages Rejet/Signalement/Paiement (norme NOEMIE-PS)</h2>
|
||||
{% if noemie %}
|
||||
<a href="./">Retourner à la liste NOEMIE</a>
|
||||
{% else %}
|
||||
<a href="../..">Retourner à la facturation</a>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
<div id="facturation-contents">
|
||||
|
||||
{% if error_message %}
|
||||
<p><span style="color: #f00;">Erreur : {{ error_message }}</span></p>
|
||||
{% endif %}
|
||||
|
||||
{% if b2_is_configured %}
|
||||
|
||||
{% if noemie %}
|
||||
<h1>{{ noemie.nature }} de {{ noemie.from }}</h1>
|
||||
le {{ noemie.date }}, sujet {{ noemie.subject }}
|
||||
|
||||
<ul>
|
||||
{% for line in noemie.data %}
|
||||
<li>
|
||||
{{ line.description }}
|
||||
<ul>
|
||||
{% for segment in line.segments %}
|
||||
<li>{{ segment.name }} : {{ segment.value }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
{% elif noemies %}
|
||||
<ul>
|
||||
{% for noemie in noemies|dictsortreversed:"date" %}
|
||||
<li><a href="{{noemie.name}}">{{noemie.date}}</a>: {{ noemie.nature }} de {{ noemie.from }} {{ noemie.subject }}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
|
||||
{% else %}
|
||||
<p><span style="color: #f00;">Système de transmission non configuré.</span></p>
|
||||
<p><a href="../..">Retourner à la facturation</a></p>
|
||||
{% endif %}
|
||||
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
|
@ -0,0 +1,94 @@
|
|||
{% extends "facturation/base.html" %}
|
||||
{% load url from future %}
|
||||
|
||||
{% block appbar %}
|
||||
<h2>
|
||||
|
||||
{% if service_name == "CMPP" %}
|
||||
Facturation {{ invoicing.seq_id }}
|
||||
{% if invoicing.status == "open" %}
|
||||
ouverte et ayant débuté le {{ invoicing.start_date }}
|
||||
{% else %}
|
||||
{% if invoicing.status == "closed" %}
|
||||
fermée
|
||||
{% else %}
|
||||
validée
|
||||
{% endif %}
|
||||
couvrant la période du {{ invoicing.start_date }} au {{ invoicing.end_date }}
|
||||
{% endif %}
|
||||
{% else %}
|
||||
Décompte {{ invoicing.seq_id }}
|
||||
{% if invoicing.status == "validated" %}
|
||||
validé
|
||||
{% endif %}
|
||||
pour le trimestre allant du {{ invoicing.start_date }} au {{ invoicing.end_date }}
|
||||
{% endif %}</h2>
|
||||
<a href="..">Retourner à la facturation {{ invoicing.seq_id }}</a>
|
||||
{% if service_name == "CMPP" %}
|
||||
{% if b2_is_configured and invoicing.status == "validated" %}
|
||||
{% if b2 %}
|
||||
<button onclick="window.location.href=window.location.href+'mail'">Transmettre à toutes les caisses</button>
|
||||
{% else %}
|
||||
<button onclick="window.location.href=window.location.href+'build'">Préparer</button>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
<div id="facturation-contents">
|
||||
|
||||
{% if b2_is_configured %}
|
||||
{% if invoicing.status == "validated" %}
|
||||
|
||||
<h1>Télétransmission de la facturation {{invoicing.seq_id}}</h1>
|
||||
|
||||
{% if error_message %}
|
||||
<p><span style="color: #f00;">Erreur : {{ error_message }}</span></p>
|
||||
|
||||
{% elif b2 %}
|
||||
{% for info in b2|dictsortreversed:"total" %}
|
||||
<h3 id="{{ info.files.b2 }}">{{ info.hc }} — {{ info.total|floatformat:2 }} €</h3>
|
||||
|
||||
{% if info.mail_date %}
|
||||
<span style="background: #4f4; color: #000;">Transmis</span> le {{ info.mail_date }} —
|
||||
<a style="color: #8c8c73;" href="mail/{{ info.files.b2 }}">Transmettre à nouveau</a>
|
||||
{% else %}
|
||||
Fichier créé le {{ info.creation_date }} —
|
||||
<a style="color: #8c8c73;" href="mail/{{ info.files.b2 }}">Transmettre à la caisse</a>
|
||||
{% endif %}
|
||||
|
||||
{% if info.mail_log %}
|
||||
{% if "MAIL SENT" in info.mail_log %}<pre>{% elif "SMTP ERROR" in info.mail_log%}<pre style="background: #f44; color: #000;">{% endif %}{{ info.mail_log }}</pre>
|
||||
{% endif %}
|
||||
|
||||
<ul>
|
||||
{% for b in info.batches %}
|
||||
<li>lot {{ b.batch }} pour {{ b.hc }}, {{ b.number_of_invoices }} factures ({{b.number_of_acts}} actes) — {{ b.total|floatformat:2 }} €</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<p>
|
||||
Cette facturation est validée, mais les fichiers de transmission (format B2) ne sont pas encore générés. Cliquer sur le bouton pour les créer :
|
||||
<button onclick="window.location.href=window.location.href+'build'">Préparer les données de télétransmission</button>
|
||||
</p>
|
||||
<p>
|
||||
Une fois les fichiers créés, vous pourrez les télé-transmettre depuis cette page.
|
||||
</p>
|
||||
{% endif %}
|
||||
|
||||
{% else %}
|
||||
Facturation non validée, transmission impossible.
|
||||
<a href="..">Retourner à la facturation {{ invoicing.seq_id }}</a>
|
||||
{% endif %}
|
||||
|
||||
{% else %}
|
||||
<p><span style="color: #f00;">Système de télétransmission non configuré.</span></p>
|
||||
<p><a href="..">Retourner à la facturation {{ invoicing.seq_id }}</a></p>
|
||||
{% endif %}
|
||||
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
|
@ -159,16 +159,16 @@ def build_mail(large_regime, dest_organism, b2_filename):
|
|||
if MODE_ENCRYPT:
|
||||
mime_part = smime(mime(b2), get_certificate(large_regime, dest_organism))
|
||||
|
||||
filename = b2_filename + '-mail'
|
||||
fd = open(filename, 'w')
|
||||
fd = StringIO.StringIO()
|
||||
for k,v in mail.items():
|
||||
fd.write('%s: %s\n' % (k,v))
|
||||
fd.write('\n')
|
||||
fd.write('--%s\n' % delimiter)
|
||||
fd.write(mime_part)
|
||||
fd.write('--%s--\n' % delimiter)
|
||||
ret = fd.getvalue()
|
||||
fd.close()
|
||||
return filename
|
||||
return ret
|
||||
|
||||
#
|
||||
# CApath construction
|
||||
|
|
|
@ -2,7 +2,9 @@ from django.conf.urls import patterns, url
|
|||
|
||||
from views import (FacturationHomepageView, FacturationDetailView,
|
||||
ValidationFacturationView, close_form, display_invoicing,
|
||||
FacturationDownloadView, FacturationExportView, rebill_form)
|
||||
FacturationDownloadView, FacturationExportView, rebill_form,
|
||||
FacturationTransmissionView, FacturationTransmissionBuildView,
|
||||
FacturationTransmissionMailView, FacturationNoemieView)
|
||||
|
||||
urlpatterns = patterns('calebasse.facturation.views',
|
||||
url(r'^$', FacturationHomepageView.as_view()),
|
||||
|
@ -10,6 +12,10 @@ urlpatterns = patterns('calebasse.facturation.views',
|
|||
url(r'^(?P<pk>\d+)/$', FacturationDetailView.as_view()),
|
||||
url(r'^(?P<pk>\d+)/download/.*$', FacturationDownloadView.as_view()),
|
||||
url(r'^(?P<pk>\d+)/export/.*$', FacturationExportView.as_view()),
|
||||
url(r'^(?P<pk>\d+)/transmission/$', FacturationTransmissionView.as_view()),
|
||||
url(r'^(?P<pk>\d+)/transmission/build/$', FacturationTransmissionBuildView.as_view()),
|
||||
url(r'^(?P<pk>\d+)/transmission/mail/(?P<b2>.*$)$', FacturationTransmissionMailView.as_view()),
|
||||
url(r'^transmission/noemie/(?P<name>.*)$', FacturationNoemieView.as_view()),
|
||||
url(r'^(?P<pk>\d+)/validate/$',
|
||||
ValidationFacturationView.as_view(),
|
||||
name='validate-facturation'),
|
||||
|
|
|
@ -13,6 +13,8 @@ from calebasse.cbv import TemplateView, UpdateView
|
|||
from models import Invoicing, Invoice
|
||||
from calebasse.ressources.models import Service
|
||||
from invoice_header import render_invoicing
|
||||
from b2 import b2_is_configured, get_all_infos, buildall, sendmail
|
||||
from noemie import noemie_mails, noemie_from_mail
|
||||
|
||||
def display_invoicing(request, *args, **kwargs):
|
||||
if request.method == 'POST':
|
||||
|
@ -210,3 +212,56 @@ class FacturationExportView(cbv.DetailView):
|
|||
response['Content-Length'] = content.size
|
||||
response['Content-Disposition'] = 'attachment; filename="export-%s.txt"' % invoicing.seq_id
|
||||
return response
|
||||
|
||||
|
||||
class FacturationTransmissionView(UpdateView):
|
||||
context_object_name = "invoicing"
|
||||
model = Invoicing
|
||||
template_name = 'facturation/transmission.html'
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super(FacturationTransmissionView, self).get_context_data(**kwargs)
|
||||
context['b2_is_configured'] = b2_is_configured()
|
||||
try:
|
||||
context['b2'] = get_all_infos(context['invoicing'].seq_id)
|
||||
except IOError, e:
|
||||
context['error_message'] = e
|
||||
return context
|
||||
|
||||
class FacturationTransmissionBuildView(cbv.DetailView):
|
||||
context_object_name = "invoicing"
|
||||
model = Invoicing
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
invoicing = self.get_object()
|
||||
if b2_is_configured() and invoicing.status == "validated":
|
||||
buildall(invoicing.seq_id)
|
||||
return HttpResponseRedirect('..')
|
||||
|
||||
class FacturationTransmissionMailView(UpdateView):
|
||||
context_object_name = "invoicing"
|
||||
model = Invoicing
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
invoicing = self.get_object()
|
||||
if b2_is_configured() and invoicing.status == "validated":
|
||||
sendmail(invoicing.seq_id, oneb2=kwargs.get('b2'))
|
||||
return HttpResponseRedirect('..')
|
||||
|
||||
|
||||
class FacturationNoemieView(TemplateView):
|
||||
template_name = 'facturation/noemie.html'
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super(FacturationNoemieView, self).get_context_data(**kwargs)
|
||||
context['b2_is_configured'] = b2_is_configured()
|
||||
if b2_is_configured():
|
||||
name = kwargs.get('name')
|
||||
try:
|
||||
if name:
|
||||
context['noemie'] = noemie_from_mail(name)
|
||||
else:
|
||||
context['noemies'] = noemie_mails()
|
||||
except IOError, e:
|
||||
context['error_message'] = e
|
||||
return context
|
||||
|
|
|
@ -277,3 +277,26 @@ RTF_REPOSITORY_DIRECTORY = None
|
|||
|
||||
# Invoicing file saving directory
|
||||
INVOICING_DIRECTORY = None
|
||||
|
||||
# IRIS/B2 transmission
|
||||
# B2_TRANSMISSION = {
|
||||
# 'output_directory': '/var/lib/calebasse/B2/',
|
||||
# # B2 informations
|
||||
# 'nom': 'CMPP FOOBAR', # mandatory
|
||||
# 'numero_emetteur': '123456789', # mandatory
|
||||
# 'norme': 'CP ',
|
||||
# 'type_emetteur': 'TE',
|
||||
# 'application': 'TR',
|
||||
# 'categorie': '189',
|
||||
# 'statut': '60',
|
||||
# 'mode_tarif': '05',
|
||||
# 'message': 'ENTROUVERT 0143350135 CALEBASSE 1307',
|
||||
# # SMTP configuration
|
||||
# 'smtp_from': 'transmission@domain.net', # mandatory
|
||||
# 'smtp_host': '127.0.0.1',
|
||||
# 'smtp_port': 25,
|
||||
# 'smtp_login': '',
|
||||
# 'smtp_password': '',
|
||||
# # delay between two mails, in seconds, or None
|
||||
# 'smtp_delay': None,
|
||||
# }
|
||||
|
|
Reference in New Issue