Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

# -*- coding: utf-8 -*- 

from math import ceil, floor 

import json 

import zipfile 

from itertools import groupby 

from pathos.multiprocessing import ProcessingPool as Pool 

 

import gpg 

from django.db.models import F, Value 

from dateutil.relativedelta import relativedelta 

from django.conf import settings 

from django.core.mail import EmailMessage 

from django.db.models import Q, Sum 

from django.db.models.functions import Coalesce 

from django.http import JsonResponse 

from django.shortcuts import HttpResponse, render 

from django.template.loader import select_template, render_to_string 

from django.template import Context 

from django.db.models.functions import Cast, Concat 

from django.db.models import FloatField 

from io import BytesIO 

from tabulate import tabulate 

from weasyprint import HTML 

from PyPDF2 import PdfFileMerger 

 

from ROOT.helper import i_request, str2bool 

from ROOT.settings import ( 

EMAIL_HOST_USER, EMAIL_MANAGING_DIRECTOR, 

GPG_HOST_USER, GPG_MANAGING_DIRECTOR, GPG_HOME, COUNTRY 

) 

from members.countryfield import COUNTRIES 

from members.models import EmailToMember, Erfa, Member, send_or_refresh_data_record, TemplateError, Person, \ 

DeliveryNumber, EmailAddress, Subscriber 

from members.forms_pa_select import AddressLabelForm 

from other.scheduler import * 

 

RETURN_TYPE_JSON = 'json' 

RETURN_TYPE_HTML = 'html' 

 

 

def _get_return_type(request): 

return_as = RETURN_TYPE_JSON 

if 'return_as' in i_request(request): 

return_as = i_request(request)['return_as'] 

return return_as 

 

 

def country_analysis(request): 

return_as = _get_return_type(request) 

country_dict = {} 

 

for member in Member.objects.members_only(): 

if member.address_country not in country_dict: 

 

country_name = '' 

for countryPair in COUNTRIES: 

if countryPair[0] == member.address_country: 

country_name = countryPair[1] 

country_dict[member.address_country] = { 

'country': member.address_country, 

'country_name': country_name, 

'members': 0 

} 

country_dict[member.address_country]['members'] += 1 

 

if return_as == RETURN_TYPE_JSON: 

json_list = [] 

for countryKey in sorted(country_dict): 

json_list.append([ 

countryKey, country_dict[countryKey]['country_name'], 

country_dict[countryKey]['members'] 

]) 

 

return HttpResponse(json.dumps(json_list), content_type='application/json') 

 

return HttpResponse('BAD FORMAT', content_type='text/html') 

 

 

def zip_analysis(_): 

national_members = Member.objects.filter(address_country=COUNTRY, address_unknown=0) 

postal_codes = (member.get_plz() for member in national_members) 

 

# sort out members without address, but no address_unknown flag 

postal_codes = (postal_code for postal_code in postal_codes if postal_code != '') 

 

postal_codes_count = groupby(sorted(postal_codes), lambda x: str(x)[:2]) 

postal_codes_count_dict = {k: len(list(v)) for k, v in postal_codes_count} 

 

result = {'total_members': national_members.count(), 'zip_codes': postal_codes_count_dict} 

 

return JsonResponse(result) 

 

 

def member_queue_data_record_email(request): 

""" 

Send a data record email to the specified Member(s) no matter if anything in their data set changed. Will refresh 

already queued emails instead of queueing multiple emails. 

:param request: Should be a GET request with one or more parameters 'chaos_number', being the chaos_number of a 

Member 

:return: A JSON string with a dictionary of each chaos number paired with either 'queued' or 'not found' 

""" 

response = {} 

for chaos_number in i_request(request).getlist('chaos_number'): 

try: 

member = Member.objects.members_only().get(chaos_number=chaos_number) 

send_or_refresh_data_record(member) 

response[chaos_number] = 'queued' 

except Member.DoesNotExist: 

response[chaos_number] = 'not found' 

return HttpResponse(json.dumps(response), content_type='application/json') 

 

 

def member_reactivate(request): 

response = {} 

for chaos_number in i_request(request).getlist('chaos_number'): 

try: 

member = Member.objects.members_only().get(chaos_number=chaos_number, is_active=False) 

member.is_active = True # Changing the is_active state and saving sets also the last_paid_date 

member.save() 

response[chaos_number] = 'reactivated' 

except Member.DoesNotExist: 

response[chaos_number] = 'not found or already active' 

return HttpResponse(json.dumps(response), content_type='application/json') 

 

 

def billing_cycle(request): 

""" 

:param request: 

:return: HttpResponse (json) 

""" 

del request 

 

booked = map(lambda member: {'member': str(member), 

'memberName': member.get_name(), 

'balance': member.account_balance} if member.execute_payment_if_due() else None, 

Member.objects.all()) 

booked = list(filter(lambda x: x is not None, booked)) 

 

return HttpResponse(json.dumps(booked), content_type='application/json') 

 

 

@daily() 

def billing_cycle_cron(): 

for member in Member.objects.all(): 

member.execute_payment_if_due() 

 

 

@daily() 

def remove_run_out_subscribers(): 

for subscriber in Subscriber.objects.all(): 

if not subscriber.will_receive_issue(settings.NEXT_DATENSCHLEUDER_ISSUE): 

subscriber.delete() 

 

 

def mail_send_next(_): 

mail_to_send = EmailToMember.objects.first() 

if mail_to_send: 

response = mail_to_send.send() 

else: 

response = {'state': 'nothing to send'} 

return HttpResponse(json.dumps(response), content_type='application/json') 

 

 

def mail_send_all(request): 

 

response = [mail.send() for mail in EmailToMember.objects.all()] 

 

if len(response) == 0: 

response = {'state': 'nothing to send'} 

 

return HttpResponse(json.dumps(response), content_type='application/json') 

 

 

def generate_letters_pa_selector(request): 

if request.method == 'POST': 

form = AddressLabelForm(request.POST) 

if form.is_valid(): 

pa_label = form.cleaned_data['pa_label'] 

return generate_letters(pa_label=pa_label) 

else: 

form = AddressLabelForm() 

return render(request, 'pa_select.html', {'form': form, 'title': 'Generate letters to members'}) 

 

 

def generate_letters(pa_label): 

""" 

Creates a zip file of undeliverable messages in the mail queue as pdf files. The pdfs are sorted by national or 

international mail and then concatenated by the number of pages to print. Messages to a member who's address is 

unknown are skipped. 

 

:return: A zip file containing messages from the mail queue as pdfs. 

""" 

data = {'national': [], 'international': []} 

 

for message in EmailToMember.objects.filter(member__emailaddress__isnull=True, 

member__address_unknown__lt=settings.ADDRESS_RETURNS).distinct(): 

del_num = DeliveryNumber(recipient=message.member, shipment='Letter on {}'.format(str(date.today()))) 

del_num.save() 

 

# Easy way to sneak it into the template 

message.member.this_delivery_number = del_num 

 

country = message.member.address_country 

template_paths = ['deadtree_templates/deadtree_base_{}.html'.format(country) 

for country in [country, 'EN']] 

 

html = render_to_string(template_paths, context={'mail': message, 'pa_label': pa_label}) 

document = HTML(string=html).render() 

 

if country == settings.COUNTRY: 

data['national'].append(document) 

else: 

data['international'].append(document) 

 

message._archive('sent as letter on {}'.format(date.today().strftime('d.m.Y'))) 

 

for letters in (l for l in data if len(l) > 0): 

d_l = data[letters] 

data[letters] = {} 

d_l.sort(key=lambda d: len(d.pages)) 

for pages, documents in groupby(d_l, key=lambda d: len(d.pages)): 

all_pages = (p for doc in documents for p in doc.pages) 

data[letters][pages] = d_l[0].copy(all_pages).write_pdf() 

 

zip_buffer = BytesIO() 

zip_file = zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) 

 

for destination in data: 

for pages in data[destination]: 

zip_file.writestr('{}/{}_pages.pdf'.format(destination, pages), data[destination][pages]) 

 

zip_file.close() 

zip_buffer.seek(0) 

response = HttpResponse(zip_buffer, content_type='application/zip') 

response['Content-Disposition'] = 'attachment; filename="letters.zip"' 

return response 

 

 

def msg_stats(_): 

stats = {} 

msgs = EmailToMember.objects.all() 

stats['msgInQ'] = msgs.count() 

 

stats['mail'] = msgs.filter(member__emailaddress__isnull=False).distinct().count() 

 

stats['letters'] = msgs.filter(member__emailaddress__isnull=True, 

member__address_unknown__lt=settings.ADDRESS_RETURNS).distinct().count() 

 

stats['unreachable'] = msgs.filter(member__emailaddress__isnull=True, 

member__address_unknown__gte=settings.ADDRESS_RETURNS).distinct().count() 

 

return HttpResponse(json.dumps(stats), content_type='application/json') 

 

 

def search_member_db(request): 

"""Handles member DB search requests returning HTML-table-rows""" 

context = {} 

if request.method == 'POST': 

params = request.POST 

check_empty_first_name = params.get('check_empty_first_name') 

check_empty_last_name = params.get('check_empty_last_name') 

check_empty_address = params.get('check_empty_address') 

check_empty_country = params.get('check_empty_country') 

check_empty_email = params.get('check_empty_email_address') 

if 'true' in (check_empty_address, check_empty_country, check_empty_first_name, check_empty_last_name, 

check_empty_email): 

# Search for empty fields 

q = Member.objects.all() 

if check_empty_first_name == 'true': 

q = q.filter(Q(first_name__exact='') | Q(first_name__isnull=True)) 

if check_empty_last_name == 'true': 

q = q.filter(Q(last_name__exact='') | Q(last_name__isnull=True)) 

if check_empty_address == 'true': 

# Filter for datasets with all three address field empty 

q = q.filter( 

( 

(Q(address_1__exact='') | 

Q(address_1__isnull=True)) & 

(Q(address_2__exact='') | 

Q(address_2__isnull=True)) & 

(Q(address_3__exact='') | 

Q(address_3__isnull=True)) 

) | Q(address_unknown__gte=settings.ADDRESS_RETURNS) 

) 

if check_empty_country == 'true': 

q = q.filter(Q(address_country__exact='') | Q(address_country__isnull=True)) 

if check_empty_email == 'true': 

q = q.exclude(emailaddress__isnull=False) 

 

context['results'] = q 

else: 

first_name = params.get('first_name', '') 

last_name = params.get('last_name', '') 

chaos_number = params.get('chaos_id', '') 

address = params.get('address', '') 

email = params.get('email_address', '') 

fee_reduced = str2bool(params.get('fee_is_reduced', 'false')) 

is_active = str2bool(params.get('is_active', 'false')) 

apply_filters = str2bool(params.get('apply_filters', 'false')) 

q = Member.objects.all() 

if first_name != '': 

q = q.filter(first_name__icontains=first_name) 

if last_name != '': 

q = q.filter(last_name__icontains=last_name) 

if chaos_number != '': # maybe check for illegal characters in the future 

q = q.filter(chaos_number=chaos_number) 

if address != '': 

q = q.filter(Q(address_1__icontains=address) | Q(address_2__icontains=address) 

| Q(address_3__icontains=address)) 

if email != '': 

q = q.filter(Q(emailaddress__email_address__icontains=email)) 

if apply_filters: 

q = q.filter(membership_reduced=fee_reduced, is_active=is_active) 

 

context['results'] = q 

return render(request, 'api/member_search_result.html', context) 

return HttpResponse('Neither Get nor Post') # HttpResponse('BAD FORMAT', content_type='text/html') 

 

 

def _erfa_statistics(): 

erfa_statistics = [ 

['Erfa', 'Mitglied', 'Förderm.', 'Ehrenm.', 'Vollzahler', 'Ermäßigt', 'Spezial', 'Vollzahler €', 'Ermäßigt €', 

'Spezial €', 'Summe €']] 

 

for erfa in Erfa.objects.all().order_by('long_name'): 

erfa_stat = [] 

 

m = Member.objects.filter(erfa=erfa) 

 

# Name of the Erfa 

erfa_stat.append(str(erfa)) 

 

# Count of different membership types 

for membership_type in [Member.MEMBERSHIP_TYPE_MEMBER, Member.MEMBERSHIP_TYPE_SUPPORTER, 

Member.MEMBERSHIP_TYPE_HONORARY]: 

erfa_stat.append(m.filter(membership_type=membership_type).count()) 

 

# Count of members by fee types 

sum_full = m.filter(fee_override__isnull=True, membership_reduced=False) 

sum_red = m.filter(fee_override__isnull=True, membership_reduced=True) 

sum_spec = m.filter(fee_override__isnull=False) 

 

erfa_stat.extend([x.count() for x in [sum_full, sum_red, sum_spec]]) 

 

# Expected fees by membership type 

erfa_stat.append(sum_full.count() * settings.FEE / 100.0) 

erfa_stat.append(sum_red.count() * settings.FEE_REDUCED / 100.0) 

erfa_stat.append(sum_spec.aggregate(spec_fee=Coalesce(Sum('fee_override'), 0))['spec_fee'] / 100.0) 

 

# Total expected fees per Erfa 

erfa_stat.append(sum(erfa_stat[-3:])) 

 

erfa_statistics.append(erfa_stat) 

 

return erfa_statistics 

 

 

def _payment_stats(): 

payment_stats = [['', 'Anzahl', 'ruhend', '>2 Monate im Rückstand', 'Ausstände >2 Monate (€)']] 

# Since the fee_paid_until field is set to when the next payment would be due, it is one year ahead of your last 

# due date. Thus we take two months off of this date (12 - 2) to get all members 2 months over their last due date. 

cut_off_date = date.today() + relativedelta(months=10) 

 

m = Member.objects.all() 

 

for membership_type, type_desc in [(Member.MEMBERSHIP_TYPE_MEMBER, 'Mitglieder'), 

(Member.MEMBERSHIP_TYPE_SUPPORTER, 'Fördermitglieder')]: 

o = m.filter(membership_type=membership_type) 

for q, desc in [(o.filter(fee_override__isnull=True, membership_reduced=False), 'Vollzahler'), 

(o.filter(fee_override__isnull=True, membership_reduced=True), 'Ermäßigt'), 

(o.filter(fee_override__isnull=False), 'Spezial')]: 

# Name and count 

line = ['{} ({})'.format(type_desc, desc), q.count()] 

 

# inactive 

line.append(q.exclude(is_active=True).count()) 

 

# Count overdue >2 months 

r = q.filter(is_active=True, account_balance__lt=0, fee_paid_until__lt=cut_off_date, 

erfa__has_doppelmitgliedschaft=False) 

line.append(r.count()) 

 

# fees overdue >2 months 

line.append(abs(r.aggregate(s=Coalesce(Sum('account_balance'), 0))['s'] / 100.0)) 

 

payment_stats.append(line) 

 

payment_stats.append( 

['Ehrenmitglieder', m.filter(membership_type=Member.MEMBERSHIP_TYPE_HONORARY).count(), 0, 0, 0]) 

 

data_grid = zip(*payment_stats[1:]) 

next(data_grid) 

payment_stats.append(['Summen'] + [sum(col) for col in data_grid]) 

 

return payment_stats 

 

 

def _datenschleuder_statistics(): 

datenschleuder_stats = [['Datenschleuder-Empfänger', 'Anzahl']] 

 

eligible_members = Member.objects.filter(Q(membership_end__isnull=True) | Q(membership_end__gt=date.today())) 

datenschleuder_stats.append(['Mitglieder', eligible_members.count()]) 

 

datenschleuder_stats.append(['- unbekannt verzogen', eligible_members.filter(address_unknown__gte=settings.ADDRESS_RETURNS).count()]) 

 

inactive_members_count = eligible_members.filter(address_unknown__lt=settings.ADDRESS_RETURNS, is_active=False).count() 

datenschleuder_stats.append(['- ruhend', inactive_members_count]) 

 

unpaid_fees_count = eligible_members.filter(address_unknown__lt=settings.ADDRESS_RETURNS, is_active=True).filter( 

Q(membership_reduced=True, account_balance__lt=-settings.FEE_REDUCED) 

| Q(membership_reduced=False, account_balance__lt=-settings.FEE)).count() 

datenschleuder_stats.append(['- Ausstände >1 Jahr', unpaid_fees_count]) 

 

sum_eligible_members = eligible_members.filter(address_unknown__lt=settings.ADDRESS_RETURNS, is_active=True).exclude( 

account_balance__lt=-settings.FEE_REDUCED, 

membership_reduced=True).exclude(account_balance__lt=-settings.FEE, membership_reduced=False).count() 

# \n\0 is a tricky way to get a spacer in. \n will cause a 2-row multi-row cell and \0 is a non-printable char, 

# which is not whitespace (whitespace is automatically removed), thus creating an empty row following this row 

datenschleuder_stats.append(['Teilsumme Mitglieder\n'+u"\u200B", sum_eligible_members]) 

 

eligible_subscribers = Subscriber.objects.all() 

datenschleuder_stats.append(['DS-Abonnenten', eligible_subscribers.count()]) 

 

address_unknown_subscribers_count = eligible_subscribers.filter(address_unknown__gte=settings.ADDRESS_RETURNS).count() 

datenschleuder_stats.append(['- unbekannt verzogen', address_unknown_subscribers_count]) 

 

run_out_subscribers_count = eligible_subscribers.exclude(address_unknown__gte=settings.ADDRESS_RETURNS).exclude( 

Q(max_datenschleuder_issue__gte=settings.NEXT_DATENSCHLEUDER_ISSUE) | Q(is_endless=True)).count() 

datenschleuder_stats.append( 

['- abgelaufen vor Ausgabe {}'.format(settings.NEXT_DATENSCHLEUDER_ISSUE), run_out_subscribers_count]) 

 

sum_eligible_subscribers = eligible_subscribers.exclude(address_unknown__gte=settings.ADDRESS_RETURNS).filter( 

Q(max_datenschleuder_issue__gte=settings.NEXT_DATENSCHLEUDER_ISSUE) | Q(is_endless=True)).count() 

datenschleuder_stats.append(['Teilsumme Abonnenten\n'+u"\u200B", sum_eligible_subscribers]) 

 

datenschleuder_stats.append(['Teilsumme Mitglieder', sum_eligible_members]) 

datenschleuder_stats.append(['Teilsumme Abonnenten', sum_eligible_subscribers]) 

datenschleuder_stats.append(['Postempfänger gesamt\n'+u"\u200B", sum_eligible_subscribers + sum_eligible_members]) 

 

datenschleuder_stats.append(['Postempfänger', sum_eligible_subscribers + sum_eligible_members]) 

sum_erfa_issues = (Erfa.objects.all().count() - 1) * 30 # "Alien" als Erfa abziehen 

datenschleuder_stats.append(['30 Stück je Erfa', sum_erfa_issues]) 

datenschleuder_stats.append( 

['Druckexemplare gesamt', sum_eligible_subscribers + sum_eligible_members + sum_erfa_issues]) 

 

return datenschleuder_stats 

 

 

@monthly() 

def _format_erfa_statistics(): 

context_dict = {'erfa_stats': tabulate(_erfa_statistics(), headers='firstrow'), 

'payment_stats': tabulate(_payment_stats(), headers='firstrow', floatfmt=['', '', '', '.2f']), 

'datenschleuder_stats': tabulate(_datenschleuder_statistics(), headers='firstrow'), 

} 

 

template = select_template(['mail_templates/mail_erfa_statistic.html', ]) 

parsed_template = template.render(context_dict) 

 

with gpg.Context(armor=True) as c: 

c.set_engine_info(gpg.constants.protocol.OpenPGP, home_dir=GPG_HOME) 

sender_key = c.get_key(GPG_HOST_USER, secret=True) 

c.signers = [sender_key] 

 

recipient_key = c.get_key(GPG_MANAGING_DIRECTOR) 

encrypted_body, _, _ = c.encrypt(parsed_template.encode(), recipients=[sender_key, recipient_key], 

always_trust=True, sign=True) 

 

send_email = EmailMessage( 

subject='Monatliche Statistik', 

body=encrypted_body.decode('utf-8'), 

from_email=EMAIL_HOST_USER, 

to=[EMAIL_MANAGING_DIRECTOR, ], 

bcc=[EMAIL_HOST_USER, ] 

) 

send_email.send(False) 

 

return parsed_template 

 

 

def get_erfa_statistics(_): 

return HttpResponse('<pre>' + _format_erfa_statistics() + '</pre>') 

 

 

@daily() 

def exit_members(): 

""" 

A daily check to remove all resigned members from the database. Resignation confirmation emails should have been 

sent already, because this routine touches every row in the database with a membership_end date in the past on every 

run. This may be inefficient, but simple. 

:return: 

""" 

for member in Member.objects.filter(Q(membership_end__isnull=False) & Q(membership_end__lte=date.today())): 

member.exit() 

 

 

@monthly() 

def send_delayed_payment_reminders(): 

for member in Member.objects.filter(is_active=True): 

if member.is_payment_late(): 

emails_in_queue = EmailToMember.objects.filter(email_type=EmailToMember.SEND_TYPE_DELAYED_PAYMENT, 

member=member) 

 

for email in emails_in_queue: 

email.render_subject_and_body() 

email.save() 

 

if not emails_in_queue: 

EmailToMember(email_type=EmailToMember.SEND_TYPE_DELAYED_PAYMENT, member=member).save() 

 

 

@daily() 

def remove_unread_email_addresses(): 

""" 

Removes the primary email address of all members who did not pay their membership fee and had no change in their 

data set since EMAIL_REMOVE_TIME months as defined in the settings. The assumption is that these members do not 

react to their primary email address and the next one should be tried. 

:return: None 

""" 

for member in Member.objects.filter(is_active=True): 

if member.account_balance < 0 and member.last_update < date.today() - relativedelta( 

months=settings.EMAIL_REMOVE_TIME): 

primary_email = member.get_emails().first() 

if primary_email: 

primary_email.delete() 

member.save() # save the member to set the last-update date to today 

 

 

def drop_transactions(request): 

# http://localhost:8000/api/drop_transactions?reallydroptransactions=yes 

_request = i_request(request) 

response = {'errorMessage': '', 'wasCleared': False, 'transactionsDropped': 0} 

if 'reallydroptransactions' in _request and _request['reallydroptransactions'] == 'yes': 

try: 

from import_app.models import Transaction 

all_transactions = Transaction.objects.all() 

count_transactions = all_transactions.count() 

all_transactions.delete() 

response['transactionsDropped'] = count_transactions 

response['wasCleared'] = True 

except Exception as ex: 

response['errorMessage'] = str(ex) 

 

return JsonResponse(response) 

 

 

def bulk_remove_members(request): 

""" 

Mass removal of unreachable members. 

:param request: Should contain the POST parameter 'chaos_numbers' as a string representing Chaos Numbers separated 

by newlines 

:return: A JSON object with a 'success' and an 'error' list of Chaos Numbers 

""" 

changes = {'success': [], 'error': []} 

if request.method == 'POST': 

lines = request.POST['chaos_numbers'].split('\n') 

for chaos_number in (line.strip() for line in lines): 

try: 

m = Member.objects.get(chaos_number__exact=chaos_number) 

if m.account_balance < 0 and not m.emailaddress_set.exists() and m.address_unknown >= settings.ADDRESS_RETURNS: 

m.account_balance = 0 

m.save() 

m.emailtomember_set.all().delete() 

m.exit() 

changes['success'].append(chaos_number) 

continue 

else: 

raise ValueError('Member is still reachable or paying membership fees') 

except Exception as e: 

changes['error'].append('{}: {}'.format(chaos_number, e)) 

return JsonResponse(changes) 

 

 

def bulk_address_unknown(request): 

""" 

Takes a list of Chaos Numbers or Datenschleuder delivery numbers, one per line, and increments these members' 

address_unknown counter. 

:param request: Should contain the POST parameter 'chaos_numbers' as a string representing Chaos Numbers or 

Datenschleuder delivery numbers separated 

by newlines 

:return: A JSON object with a 'success' and an 'error' list of Chaos Numbers and Datenschleuder delivery numbers, 

including error messages for the latter. 

""" 

changes = {'success': [], 'error': []} 

if request.method == 'POST': 

lines = request.POST['chaos_numbers'].split('\n') 

for input_number in (line.strip() for line in lines): 

try: 

588 ↛ 589line 588 didn't jump to line 589, because the condition on line 588 was never true if input_number[0].upper() == 'D': 

del_num = DeliveryNumber.objects.get(number__exact=input_number.upper()) 

if del_num.returned: 

raise ValueError('Delivery number has been processed previously') 

chaos_number = del_num.recipient.chaos_number 

del_num.returned = True 

del_num.save() 

else: 

chaos_number = input_number 

 

p = Person.objects.get(chaos_number__exact=chaos_number) 

p.address_unknown += 1 

p.save() 

changes['success'].append(chaos_number) 

except Exception as e: 

changes['error'].append("{}: {}".format(input_number, e)) 

return JsonResponse(changes) 

 

 

def bulk_email_unknown(request): 

""" 

Takes a list of e-mail addresses, one per line, and remove them from the members' datasets. 

:param request: Should contain the POST parameter 'emails' as a string representing e-mail addresses separated 

by newlines 

:return: A JSON object with a 'success' and an 'error' list of e-mail addresses, including error messages. 

""" 

changes = {'success': [], 'error': []} 

if request.method == 'POST': 

lines = request.POST['emails'].split('\n') 

for email in (line.strip() for line in lines): 

try: 

e = EmailAddress.objects.get(email_address=email) 

e.delete() 

changes['success'].append(email) 

except Exception as e: 

changes['error'].append("{}: {}".format(email, e)) 

return JsonResponse(changes) 

 

 

def mass_reactivation_reminder(_): 

""" 

Sends an e-mail to all inactive members asking them to either end their membership or activating again. This 

method is meant to be removed when no inactive members are left. 

:return: JSON list of Chaos Numbers and comments of inactive members who were mailed 

""" 

response = {'reminded members': []} 

for member in Member.objects.filter(is_active=False, membership_end=None, erfa__has_doppelmitgliedschaft=False): 

EmailToMember(email_type=EmailToMember.SEND_TYPE_REACTIVATION_REMINDER, member=member).save() 

response['reminded members'].append("{}: {}".format(member.chaos_number, member.comment)) 

 

return JsonResponse(response) 

 

 

def no_contact(request): 

""" 

Find all members who neither have a known address nor any e-mail address and are overdue with their fees. 

:return: Text file with a table holding the full dataset of the members without contact information. 

""" 

members_no_contact = Member.objects.filter(address_unknown__gte=settings.ADDRESS_RETURNS, emailaddress=None, 

erfa__has_doppelmitgliedschaft=False).annotate( 

erfa_name=F("erfa_id__short_name")).annotate(konto=Cast(F("account_balance"), FloatField()) / 100).annotate( 

address=Concat(F("address_1"), Value(', '), F("address_2"), Value(', '), F("address_3")) 

) 

 

# Filter for all members who are overdue by the supplied number of months. 12 is default. 

# The trick is to get all those members' chaosnumbers from the database and then filter by these 

months = int(request.GET.get('months_overdue', default=12)) 

cut_off_date = date.today() - relativedelta(months=months) 

overdue_member_cnr = [member.chaos_number for member in members_no_contact if 

member.is_payment_late(cut_off_date=cut_off_date)] 

members_no_contact = members_no_contact.filter(chaos_number__in=overdue_member_cnr) 

 

members_no_contact = members_no_contact.values_list("chaos_number", "erfa_name", "first_name", "last_name", 

"address", "address_country", "is_active", "membership_reduced", 

"membership_start", "fee_last_paid", "konto", "comment") 

 

headers = ["Cnr", "Erfa", "Vorname", "Nachname", "Adresse", "Land", "aktiv", "ermäßigt", 

"eingetreten am", "zuletzt gezahlt am", "Guthaben", "Kommentar"] 

table = tabulate(members_no_contact, headers=headers, floatfmt=".2f") 

 

response = HttpResponse(table, content_type='text/plain') 

response['Content-Disposition'] = 'attachment; filename="unreachable members with overdue fees.txt"' 

return response 

 

 

def ga_invitations(pa_label): 

 

def render_template(context): 

""" 

Selects a template and renders it's subject and body sections. 

 

:param country_code: Two letter country code. Is appended to the template file name with an underline. EN is 

fallback if none is found. 

:param context: Depends on the objects used in the template. 

:return: subject and body of the email as a tuple of strings. 

""" 

template_paths = ['mail_templates/mail_ga_invitation_html_DE.html'] 

 

nodes = dict((n.name, n) for n in select_template(template_paths).template.nodelist 

if n.__class__.__name__ == 'BlockNode') 

 

try: 

return nodes['subject'].render(context), nodes['body'].render(context) 

except KeyError as ke: 

raise TemplateError('Template is missing a {{% block {} %}}'.format(str(ke)[1:-1])) 

 

def generate_pdf(member): 

class Message: 

def __init__(self): 

self.member = None 

self.subject = None 

self.body = None 

 

print('Generating invitation for member {}.'.format(member.chaos_number)) 

 

del_num = DeliveryNumber(recipient=member, shipment='AMV 2019') 

del_num.save() 

# Simple method to bring this number to the template 

member.this_delivery_number = del_num.number 

 

template_paths = ['deadtree_templates/ga_invite_DE.html'] 

 

message = Message() 

message.member = member 

message.subject, message.body = render_template(Context({'member': member})) 

 

html = render_to_string(template_paths, context={'mail': message, 'pa_label': pa_label}) 

document = HTML(string=html).render() 

pages = len(document.pages) 

pdf = document.write_pdf() 

 

return pdf, pages, member.address_country == settings.COUNTRY 

 

pool = Pool() 

pdfs = pool.map(generate_pdf, Member.objects.members_only()) 

 

data = {'national': [], 'international': []} 

 

for pdf, pages, is_national in pdfs: 

if is_national: 

data['national'].append((pdf, pages)) 

else: 

data['international'].append((pdf, pages)) 

 

for letters in (l for l in data if len(l) > 0): 

d_l = data[letters] 

data[letters] = {} 

d_l.sort(key=lambda d: d[1]) 

for pages, documents in groupby(d_l, key=lambda d: d[1]): 

pages_pdf_buffer = BytesIO() 

merger = PdfFileMerger() 

 

for doc in documents: 

pdf_buffer = BytesIO() 

pdf_buffer.write(doc[0]) 

pdf_buffer.seek(0) 

 

merger.append(pdf_buffer) 

 

merger.write(pages_pdf_buffer) 

pages_pdf_buffer.seek(0) 

data[letters][pages] = pages_pdf_buffer.read() 

 

zip_buffer = BytesIO() 

zip_file = zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) 

 

for destination in data: 

for pages in data[destination]: 

zip_file.writestr('{}/{}_pages.pdf'.format(destination, pages), data[destination][pages]) 

 

zip_file.close() 

zip_buffer.seek(0) 

response = HttpResponse(zip_buffer, content_type='application/zip') 

response['Content-Disposition'] = 'attachment; filename="ga_invitations.zip"' 

return response 

 

 

def generate_pdf_from_html(html_template: str, context: dict): 

filled_in_template = render_to_string(html_template, context=context) 

rendered_html = HTML(string=filled_in_template).render() 

return rendered_html.write_pdf() 

 

 

def datenschleuder_address_stickers(_, pa_label, num_pages, pickup_date): 

""" 

This method generates the address labels for all recipients of a Datenschleuder. This is determined by the config 

setting NEXT_DATENSCHLEUDER_ISSUE and the return value of will_receive_issue() on every Person in the database. 

The resulting PDF will be ready for printing on DIN-A4 label sheets with 3x7 labels. The addresses are sorted by 

German recipients and rest of the world. Within the German recipients they are sorted by the first two numbers of 

the postal code as returned by get_plz() from 00 to 99. 

 

:return: A PDF file containing the Datenschleuder address labels 

""" 

recipients = filter(lambda person: person.will_receive_issue(settings.NEXT_DATENSCHLEUDER_ISSUE), 

Person.objects.all()) 

 

germany, world = [], [] 

for r in recipients: 

# DeliveryNumbers are stored for checking returned mail later on 

del_num = DeliveryNumber(recipient=r, shipment='DS{}'.format(settings.NEXT_DATENSCHLEUDER_ISSUE)) 

del_num.save() 

# Simple method to bring this number to the template 

r.this_delivery_number = del_num.number 

 

germany.append(r) if r.address_country == 'DE' else world.append(r) 

 

german_recipients = sorted(germany, key=lambda x: x.get_plz()) 

 

plz_regions = [] 

for plz_region, recipients_in_plz_region in groupby(german_recipients, key=lambda x: x.get_plz()[:2]): 

plz_regions.append(list(recipients_in_plz_region)) 

 

# Calculating some information about the printed magazine for delivery 

# Weights taken from http://papiergewichtrechner.de/ 

# Thickness calculation taken from https://print-assistant.de/tools/press/papierstaerke-berechnen/ 

# Post container size taken from https://shop.deutschepost.de/postbehaelter-typ-2-grau 

 

grams_inner_page = 3.7296 # DIN-A4 at 120g/m² 

grams_outer_page = 9.3240 # DIN-A4 at 300g/m² 

grams_envelope = 8.9035 # DIN-C5 envelope, i. e. two pages at 120g/m² 

grams_issue = ceil((num_pages / 2 - 2) * grams_inner_page + 2 * grams_outer_page + grams_envelope) 

 

# Volume factors provided by Pinguin Druck 

mm_thickness_120 = 0.14 # 1.2 times volume 

mm_thickness_300 = 0.312 # 1.04 times volume 

 

# Page 25 on the bottom says maximum weight of 10kg per box: 

# https://www.direktmarketingcenter.de/fileadmin/Download-Center/DIALOGPOST_National_-_Produktbroschuere_-_Stand_April_2017.pdf 

# 

# Information about Postbehälter Typ 2: https://shop.deutschepost.de/postbehaelter-typ-2-grau 

mm_box_length = 470 

grams_box_weight = 1600 

grams_box_max_weight = 10000 

grams_payload_weight = grams_box_max_weight - grams_box_weight 

 

boxes_per_cart = 20 # And 32 if empty. Asked the Deutsche Post at 0800 999 8888 about it. 

 

# All inner pages + envelope + outer pages 

mm_thickness_issue = num_pages / 2 * mm_thickness_120 + 2 * mm_thickness_300 

boxes_per_plz_region = {pr[0].get_plz()[:2]: ceil(len(pr) * mm_thickness_issue / mm_box_length) for pr in 

plz_regions} 

max_issues_per_box = min(floor(mm_box_length / mm_thickness_issue), floor(grams_payload_weight / grams_issue)) 

boxes_international = ceil(len(world) / max_issues_per_box) 

boxes_national = sum(boxes_per_plz_region.values()) 

 

delivery_paper_info = { 

'issue': settings.NEXT_DATENSCHLEUDER_ISSUE, 

'weight_grams': grams_issue, 

'thickness_mm': round(mm_thickness_issue, 1), 

'carts': ceil(boxes_national / boxes_per_cart) + ceil(boxes_international / boxes_per_cart), 

'action_nat': 'Datenschleuder {} national'.format(settings.NEXT_DATENSCHLEUDER_ISSUE), 

'recipients_national': len(germany), 

'boxes_total_nat': boxes_national, 

'action_int': 'Datenschleuder {} international'.format(settings.NEXT_DATENSCHLEUDER_ISSUE), 

'recipients_international': len(world), 

'boxes_total_int': boxes_international, 

} 

 

box_labels_nat = [] 

box_num = 0 

 

for plz_region in plz_regions: 

 

num_plz_boxes = ceil(len(plz_region) / max_issues_per_box) 

 

for box_num_plz in range(1, num_plz_boxes + 1): 

 

issues_left_to_box = len(plz_region) - (box_num_plz - 1) * max_issues_per_box 

box_num += 1 

 

box_labels_nat.append({ 

'action_name': delivery_paper_info['action_nat'], 

'date': pickup_date.strftime('%d.%m.%Y'), 

'box_num': box_num, 

'total_boxes': boxes_national, 

'plz': str(plz_region[0].get_plz()[:2]), 

'cart_num': floor(box_num / boxes_per_cart) + 1, 

'num_issues': min(max_issues_per_box, issues_left_to_box), 

}) 

 

box_labels_int = [ 

{ 

'action_name': delivery_paper_info['action_int'], 

'date': pickup_date.strftime('%d.%m.%Y'), 

'box_num': box_num, 

'total_boxes': boxes_international, 

'plz': 'international', 

'cart_num': floor(box_num/boxes_per_cart) + 1, 

'num_issues': len(world) % max_issues_per_box if box_num == boxes_international else max_issues_per_box, 

} 

for box_num in range(1, boxes_international + 1) 

] 

 

# Append the world recipients here so they are not part of the box label generation for national recipients, 

# but are part of the print label generation 

plz_regions.append(world) 

 

fv_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 

"../../static/images/DP_VerkVermerk_DiP_NAT.jpg") 

 

address_labels_pdf = generate_pdf_from_html(html_template='deadtree_templates/ds_addresses_DE.html', 

context={'plz_regions': plz_regions, 'pa_label': pa_label, 

'fv_path': fv_path}) 

 

delivery_info_pdf = generate_pdf_from_html(html_template='deadtree_templates/ds_delivery_info.html', 

context={'delivery_info': delivery_paper_info}) 

 

box_labels_nat_pdf = generate_pdf_from_html(html_template='deadtree_templates/ds_box_labels.html', 

context={'box_labels': box_labels_nat}) 

 

box_labels_int_pdf = generate_pdf_from_html(html_template='deadtree_templates/ds_box_labels.html', 

context={'box_labels': box_labels_int}) 

 

zip_buffer = BytesIO() 

zip_file = zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) 

 

zip_file.writestr('Lieferscheininformationen.pdf', delivery_info_pdf) 

zip_file.writestr('Behälterbeschriftungen national.pdf', box_labels_nat_pdf) 

zip_file.writestr('Behälterbeschriftungen international.pdf', box_labels_int_pdf) 

zip_file.writestr('Adressaufkleber.pdf', address_labels_pdf) 

 

zip_file.close() 

zip_buffer.seek(0) 

response = HttpResponse(zip_buffer, content_type='application/zip') 

response['Content-Disposition'] = 'attachment; filename="ds_versand.zip"' 

return response 

 

 

def ga_emails(_): 

""" 

Send the general assembly invitation as email. 

:return: JSON list of Chaos Numbers and comments of members who an email was sent to 

""" 

 

chaos_numbers = [] 

 

for member in Member.objects.members_only().filter(emailaddress__isnull=False): 

if EmailToMember.objects.filter(email_type=EmailToMember.SEND_TYPE_GA_INVITATION, member=member).exists(): 

continue 

EmailToMember(email_type=EmailToMember.SEND_TYPE_GA_INVITATION, member=member).save() 

print('Sending GA invitation for member {}'.format(member.chaos_number)) 

chaos_numbers.append(member.chaos_number) 

 

return JsonResponse({'Mails sent to': chaos_numbers})