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

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

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

import datetime 

import logging 

 

import re 

import qrcode 

import base64 

import random 

import textwrap 

from . import word_list 

from io import BytesIO 

 

from dateutil.relativedelta import relativedelta 

from django.conf import settings 

from django.core.exceptions import ValidationError 

from django.core.mail import EmailMessage 

from django.core.validators import RegexValidator 

from django.utils.crypto import get_random_string 

from django.db import models 

from django.db.models import Q 

from django.db.models.signals import post_save 

from django.template import Context, loader 

from django.template.loader_tags import BlockNode, ExtendsNode 

from members.countryfield import CountryField 

from dirtyfields import DirtyFieldsMixin 

from polymorphic.models import PolymorphicModel, PolymorphicManager 

from other.gpg_util import sign_message, PublicKey, KeyStatus as KS, KeyRefreshStatus as KRS 

 

 

class MemberManager(PolymorphicManager): 

def members_only(self): 

# ATTENTION: if you change this logic, you have to change the corresponding logic in Member.is_member 

return self.get_queryset().filter( 

Q(membership_end__isnull=True) 

| Q(membership_end__gt=datetime.datetime.now())) 

 

 

class Erfa(models.Model): 

# We use shortname in part as filename, e.g. we don't want any spaces and or dots. 

short_name = models.SlugField(blank=False, 

null=False, 

unique=True, 

max_length=255) 

long_name = models.CharField(blank=False, 

null=False, 

unique=True, 

max_length=255) 

has_doppelmitgliedschaft = models.BooleanField(default=False) 

 

def __str__(self): 

desc = self.short_name 

if len(self.long_name) > 0: 

desc += ' (' + self.long_name + ')' 

if self.has_doppelmitgliedschaft: 

desc += ' Doppelmitgliedschaft' 

return desc 

 

 

def get_alien(): 

return Erfa.objects.get_or_create(short_name='Alien')[0].id 

 

 

class Person(DirtyFieldsMixin, PolymorphicModel): 

""" 

Basis for members and Datenschleuder subscribers. Has all the fields shared between them. 

""" 

chaos_number = models.AutoField(primary_key=True) 

 

first_name = models.CharField(blank=False, null=False, max_length=255) 

last_name = models.CharField(blank=False, null=False, max_length=255) 

 

address_1 = models.CharField(blank=False, null=False, max_length=255) 

address_2 = models.CharField(blank=True, null=True, max_length=255) 

address_3 = models.CharField(blank=True, null=True, max_length=255) 

address_country = CountryField() 

 

# Counter for returned snail mail 

address_unknown = models.PositiveIntegerField(blank=False, 

null=False, 

default=0) 

address_unknown.help_text = 'Counter of returned snail mail. {} or more will '.format(settings.ADDRESS_RETURNS) + \ 

'be considered as unreachable. Is automatically reset to 0 when modifying any part' + \ 

'of the address' 

 

def get_address(self, separator=' '): 

if self.address_unknown >= settings.ADDRESS_RETURNS: 

return 'unknown' 

 

parts = [self.address_1, self.address_2, self.address_3] 

return separator.join(p for p in parts if p is not None) 

 

get_address.short_description = 'Address' 

get_address.admin_order_field = 'address_1' 

 

def is_international(self): 

return self.address_country != settings.COUNTRY 

 

def get_name(self): 

return '{} {}'.format(self.first_name, self.last_name) 

 

get_name.short_description = 'Full name' 

get_name.admin_order_field = 'first_name' 

 

def get_plz(self): 

""" 

Tries to find the postal code in the address dataset. Only meant to work in German addresses and requires the 

postal code to be on the last line of the address. 

:return: 5-digit postal code as string 

""" 

last_address_line = self.address_3 if self.address_3 else self.address_2 

match = re.search(r'^\d{4,5} ', str(last_address_line)) 

return '{:05d}'.format(int(match.group())) if match else '' 

 

def get_emails(self): 

""" 

Returns all email addresses of this member. 

:return: A list with the primary email address in the first position, then the addresses with a gpg key, if 

there are any and lastly emails addresses without a gpg key. 

""" 

return self.emailaddress_set.all().order_by('-is_primary', 

'-gpg_key_id') 

 

def get_emails_string(self): 

all_emails = self.get_emails() 

if all_emails: 

return ', '.join(str(x) for x in all_emails) 

else: 

return '- (PGP: none)' 

 

get_emails_string.short_description = 'E-Mail(s)' 

get_emails_string.admin_order_field = 'email' 

 

def email_is_unknown(self): 

return not self.emailaddress_set.all().exists() 

 

def get_primary_mail(self): 

primary_mail = self.emailaddress_set.filter(is_primary=True).first() 

if primary_mail: 

return primary_mail 

general_mail = self.emailaddress_set.first() 

if general_mail: 

general_mail.is_primary = True 

general_mail.save() 

return general_mail 

 

def will_receive_issue(self, issue): 

""" 

Should this person be sent a (certain) issue of the Datenschleuder 

 

:param issue: Number of the Datenschleuder which should be determined to send 

:return: If the member has not more than one year overdue fees, is active and has not exited yet 

""" 

raise NotImplementedError("Please Implement this method") 

 

def save(self, *args, **kwargs): 

# If the address was formerly unknown and now any part of it has been changed, but the address_unknown field has 

# not been unchecked, then assume it has been forgotten and uncheck that field automatically. 

if any(field in ['address_1', 'address_2', 'address_3', 'address_country'] for field in 

self.get_dirty_fields()) and self._original_state['address_unknown']\ 

and 'address_unknown' not in self.get_dirty_fields(): 

self.address_unknown = 0 

 

super().save(*args, **kwargs) 

 

 

class Subscriber(Person): 

IMPORT_INITIAL = 'SYN' 

UNKNOWN_SOURCE = 'UKS' 

 

SUBSCRIBER_SOURCE_CHOICES = ( 

(UNKNOWN_SOURCE, 'UNKNOWN SOURCE'), 

(IMPORT_INITIAL, 'INITIAL IMPORT'), 

) 

subscriber_source = models.CharField(max_length=3, 

choices=SUBSCRIBER_SOURCE_CHOICES) 

 

max_datenschleuder_issue = models.IntegerField( 

blank=False, null=False, default=0) # inclusive last number 

max_datenschleuder_issue.short_desciption = 'number of the latest isssue this person will get (inclusive!)' 

 

is_endless = models.BooleanField(default=False) 

is_endless.short_description = 'free subscription' 

 

rt_link = models.URLField(max_length=60, null=True, blank=True, default='') 

 

def __str__(self): 

desc = str( 

self.chaos_number) + ': ' + self.first_name + ' ' + self.last_name 

if self.is_endless: 

desc += ' (endless subscription)' 

else: 

desc += ' (' + str(self.max_datenschleuder_issue) + ')' 

return desc 

 

def will_receive_issue(self, issue): 

return (self.is_endless or self.max_datenschleuder_issue >= issue 

) and not self.address_unknown >= settings.ADDRESS_RETURNS 

 

# abo: x-ausgaben (def 8) 

# until issue number (example: 106) 

# 999 endless 

# bei export musss aktuelle datenschleuder nr angegeben werden!!!1! 

 

 

def generate_transfer_token() -> str: 

"""Generates a random token for transfers to be used in payments for the CCC 

 

The tokens are in the form of '<prefix>XXXXXX' where X denotes a random char from this alphabet: ACDEFHKLMNPRWX39 

This alphabet has been chosen to be compatible with SEPA transfer character sets and to minimize mistakes 

through similar letters and/or numbers. 

<prefix> is defined in the project's settings.py or production_settings.py. 

 

The returned token is not guaranteed to be unique. 

""" 

token_alphabet = 'ACDEFHKLMNPRWX39' 

length = 6 

prefix = settings.TRANSFER_TOKEN_PREFIX 

 

return prefix + get_random_string(length, token_alphabet) 

 

 

def generate_abstimmung_token() -> str: 

"""Generates a random token for Abstimmungen to verify legitimacy 

 

The returned token is not guaranteed to be unique. 

""" 

return get_random_string(length=10, allowed_chars='abcdefghijklmnopqrstuvwxyz') 

 

 

def _initial_password(): 

alphabet = 'ABCDEFGHKLMNPQRSTUVWXYZabcdefghikmnopqrstuvwxyz23456789-_!?#*${}()<>[]:=&@%+' 

initial_password = get_random_string(13, alphabet) 

return initial_password 

 

 

def _unique_username(): 

while True: 

username = '.'.join([ 

random.choice(word_list.adjective_list), 

random.choice(word_list.nouns) 

]) 

if not Member.objects.filter(username=username).exists(): 

return username 

 

 

class Member(Person): 

""" 

This model represents a person, that is or was a member of the association. 

""" 

 

transfer_token = models.CharField(max_length=9, 

default=generate_transfer_token, 

unique=True, 

null=False, 

blank=False) 

initial_password = models.CharField(max_length=13, 

unique=False, 

default=_initial_password, 

blank=False, 

null=False) 

 

username = models.CharField(max_length=50, 

default=_unique_username, 

unique=True, 

null=False, 

blank=False) 

 

def human_readable_transfer_token(self): 

"""Add dashes every 3 characters for better readability """ 

return '-'.join(textwrap.wrap(self.transfer_token, 3)) 

 

MEMBERSHIP_TYPE_SUPPORTER = 'SUP' 

MEMBERSHIP_TYPE_MEMBER = 'MBR' 

MEMBERSHIP_TYPE_HONORARY = 'HON' 

 

MEMBERSHIP_TYPE_CHOICES = [ 

(MEMBERSHIP_TYPE_SUPPORTER, 'SUPPORTER'), 

(MEMBERSHIP_TYPE_MEMBER, 'MEMBER'), 

(MEMBERSHIP_TYPE_HONORARY, 'HONORARY'), 

] 

 

membership_type = models.CharField(max_length=3, 

choices=MEMBERSHIP_TYPE_CHOICES, 

default=MEMBERSHIP_TYPE_SUPPORTER) 

 

is_active = models.BooleanField(default=True) 

 

membership_reduced = models.BooleanField(default=False) 

membership_reduced.short_description = 'ermäßigte mitgliedschaft / mitgliedschaft' 

 

erfa = models.ForeignKey(Erfa, 

blank=False, 

null=False, 

default=get_alien, 

on_delete=models.CASCADE) 

 

# only admin should change it 

membership_start = models.DateField(blank=False, 

null=False, 

default=datetime.date.today) 

 

# invis 

membership_end = models.DateField(blank=True, null=True) 

fee_last_paid = models.DateField(blank=True, null=True) 

fee_paid_until = models.DateField(blank=False, 

null=False, 

default=datetime.date.today) 

last_update = models.DateField(auto_now=True) 

account_balance = models.IntegerField(blank=False, null=False, default=0) 

account_balance.short_description = 'value is in cent' 

fee_override = models.IntegerField(blank=True, null=True, default=None) 

fee_override.short_description = 'Jährlicher, individueller Mitgliedsbeitrag, Überschreibt ALLE anderen Werte!' 

 

fee_registration_paid = models.BooleanField(default=False) 

 

notification_consent = models.BooleanField(default=False) 

wants_datenschleuder = models.BooleanField(default=True) 

 

comment = models.CharField(blank=True, null=False, max_length=255) 

 

# other non-var stuff 

objects = MemberManager() 

 

def __str__(self): 

if not self.is_member(): 

membership = 'exited' 

elif not self.is_active: 

membership = 'inactive' 

else: 

membership = 'active' 

 

return 'Member {} {}'.format(self.chaos_number, membership) 

 

def qrcode_b64(self) -> str: 

""" 

Chaos Number in a machine-readable format. Useful to scan from letters and such. 

:return: A base64-encoded PNG of a QR code containing the Chaos Number. 

""" 

img = qrcode.make(str(self.chaos_number) + "\r", box_size=5) 

buffered = BytesIO() 

img.save(buffered, format="PNG") 

return base64.b64encode(buffered.getvalue()).decode('utf-8') 

 

def abstimmungstoken_qrcode_b64(self) -> str: 

""" 

Abstimmungs-Token in a machine-readable format. Useful to scan from letters and such. 

:return: A base64-encoded PNG of a QR code containing the Abstimmungs-Token. 

""" 

img = qrcode.make(str(AbstimmungToken.objects.filter(member=self).first().token) + "\r", box_size=4, border=2) 

buffered = BytesIO() 

img.save(buffered, format="PNG") 

return base64.b64encode(buffered.getvalue()).decode('utf-8') 

 

def is_member(self): 

# ATTENTION: if you change this logic, you have to change the corresponding logic in MemberManager.members_only 

return (self.membership_end is None) or (datetime.date.today() < 

self.membership_end) 

 

is_member.short_description = 'is member' 

 

def is_payment_late(self, 

cut_off_date=datetime.date.today() - 

relativedelta(months=2)): 

# This is the cut off date plus one year, because members who paid recently 

# have a fee_paid_until set to exactly one year after their last due date. 

payday = cut_off_date + relativedelta(years=1) 

 

368 ↛ 369line 368 didn't jump to line 369, because the condition on line 368 was never true if not self.is_active: 

return False 

else: 

if self.fee_paid_until < datetime.date.today(): 

self.execute_payment_if_due() 

if self.account_balance >= 0 or self.erfa.has_doppelmitgliedschaft: 

return False 

elif self.account_balance < -self.get_annual_fee(): 

return True 

else: 

# between -fee and 0 

if self.fee_paid_until >= payday: 

return False 

else: 

return True 

 

@property 

def has_further_fees_due(self) -> bool: 

""" 

Determines if a member will have to pay another membership fee in the future. Most likely to be True, but when a 

member leaves the club with an early advance notice, he or she might need to pay another fee before leaving the 

club. 

 

:return: True, if the member will have to pay another fee and False if the membership is already paid until its 

exit date 

""" 

394 ↛ 395line 394 didn't jump to line 395, because the condition on line 394 was never true if self.membership_end and self.membership_end < self.fee_paid_until: 

return False 

return True 

 

def will_receive_issue(self, _=None): 

return not self.is_payment_late(cut_off_date=datetime.date.today() - relativedelta(years=1)) \ 

and self.is_active and self.is_member() and not self.address_unknown >= settings.ADDRESS_RETURNS \ 

and self.wants_datenschleuder 

 

def get_fees_payable_until_2021_04_24(self): 

if not self.is_active: 

return self.get_annual_fee_readable() 

 

until_date = datetime.date(2021, 4, 24) 

fees_payable = -self.account_balance 

if self.fee_paid_until <= until_date: 

years_until = relativedelta(until_date, 

self.fee_paid_until).years + 1 

fees_payable += years_until * self.get_annual_fee() 

return '{:0.2f}'.format(fees_payable / 

float(100) if fees_payable > 0 else 0) 

 

def get_balance_readable(self): 

return '{:0.2f}'.format(float(self.account_balance) / 100.0) 

 

def get_debts_readable(self): 

return '{:0.2f}'.format(float(self.account_balance) / -100.0) 

 

def get_annual_fee(self): 

if self.membership_type == self.MEMBERSHIP_TYPE_HONORARY: 

return 0 

if self.fee_override is not None: 

return self.fee_override 

elif self.membership_reduced: 

return settings.FEE_REDUCED 

return settings.FEE 

 

def get_annual_fee_readable(self): 

return '{:0.2f}'.format(self.get_annual_fee() / 100) 

 

def alienate(self, erfa): 

if self.erfa != erfa: 

return False 

erfa, created = Erfa.objects.get_or_create( 

short_name=settings.EMPTY_ERFA_NAME) 

if created: 

erfa.long_name = settings.EMPTY_ERFA_NAME 

# TODO: do we need this? please test if child objects are automatically saved 

erfa.safe() 

self.erfa = erfa 

 

def exit(self): 

""" 

Resign a member. The dataset is kept until any outstanding fees are settled. 

The resignation confirmation email has to be sent separately. 

:return: 

""" 

 

# Members with unsettled fees are just not yet deleted 

453 ↛ 454line 453 didn't jump to line 454, because the condition on line 453 was never true if self.account_balance < 0: 

if self.membership_end is None: 

# everything except TODAY makes problems with "members_only" and "is_member" 

self.membership_end = datetime.date.today() 

self.save() 

return 

 

# ToDo: Maybe here we could send a "your account is settled, we will delete your data now" mail. 

 

try: 

self.delete() 

except models.deletion.ProtectedError as e: 

print(e) 

pass 

 

def set_balance_to(self, 

new_balance, 

reason=None, 

comment='', 

booking_day=None, 

save=True): 

# calculates transaction and passes to increaseBalanceBy 

increase_by = new_balance - self.account_balance 

self.increase_balance_by(increase_by, reason, comment, booking_day, 

save) 

 

def increase_balance_by(self, 

increase_by, 

reason=None, 

comment='', 

booking_day=None, 

save=True, 

bank_transaction=None): 

# all booked balance changes should occur via this function 

self.account_balance += increase_by 

if booking_day: 

self.fee_last_paid = booking_day 

logging.info('increasing balance of member: {} by: {}'.format( 

self.chaos_number, increase_by)) 

self.log_increased_balance(increase_by, reason, comment, booking_day, 

bank_transaction) 

494 ↛ exitline 494 didn't return from function 'increase_balance_by', because the condition on line 494 was never false if save: 

self.save() 

 

def log_increased_balance(self, 

increased_by, 

reason=None, 

comment='', 

booking_day=None, 

bank_transaction=None): 

transaction_log = BalanceTransactionLog() 

logging.info('balance used to be {}'.format( 

self._original_state['account_balance'])) 

transaction_log.save_log(member=self, 

amount=increased_by, 

new_value=self.account_balance, 

comment=comment, 

reason=reason, 

booking_day=booking_day, 

bank_transaction=bank_transaction) 

 

def execute_payment_if_due(self, save=True): 

""" 

Checks if the next annual fee is due and processes it, if enough money is in the account_balance. 

:return: True, if a payment has been processed, False otherwise. 

""" 

519 ↛ 520line 519 didn't jump to line 520, because the condition on line 519 was never true if self.membership_type == self.MEMBERSHIP_TYPE_HONORARY or not self.is_active: 

return False 

 

# In case the member already declared its resignation and the fees until the resignation date are paid do 

# nothing. 

524 ↛ 525line 524 didn't jump to line 525, because the condition on line 524 was never true if self.membership_end and self.membership_end <= self.fee_paid_until: 

return False 

 

# Do not run on the same date because that would cause to run it the day a new member was entered and we 

# know for sure no money arrived yet (except in the Vereinstisch case). 

# Everything is okay, go ahead and "transform" money to membership years 

530 ↛ 545line 530 didn't jump to line 545, because the condition on line 530 was never false if self.fee_paid_until < datetime.date.today(): 

years = relativedelta(datetime.date.today(), 

self.fee_paid_until).years + 1 

# keep this order because increase_balance_by calls save() 

previous_due_date = self.fee_paid_until 

self.fee_paid_until += relativedelta(years=years) 

self.increase_balance_by( 

-self.get_annual_fee() * years, 

reason=BalanceTransactionLog.BILLING_CYCLE, 

save=save, 

comment= 

'Previous due date: {:%d.%m.%Y}. New due date: {:%d.%m.%Y}.'. 

format(previous_due_date, self.fee_paid_until)) 

return True 

else: 

return False 

 

def save(self, *args, **kwargs): 

# Ensure the transfer_token is unique 

549 ↛ 552line 549 didn't jump to line 552, because the condition on line 549 was never true while Member.objects.filter( 

transfer_token=self.transfer_token).exclude( 

pk=self.pk).exists(): 

self.transfer_token = generate_transfer_token() 

 

# If a payment arrives while the member is inactive, then activate it 

if self._original_state[ 

'account_balance'] < self.account_balance and not self.is_active: 

self.is_active = True 

 

# On reactivation of a member their payment due date should be set as if they were a new member 

# The account balances are set to 0 by a database migration and need no adjustment 

561 ↛ 563line 561 didn't jump to line 563, because the condition on line 561 was never true if not self._original_state[ 

'is_active'] and 'is_active' in self.get_dirty_fields(): 

self.fee_paid_until = datetime.date.today() 

 

super().save(*args, **kwargs) 

 

def clean(self): 

# If an Erfa with Doppelmitgliedschaft is chosen, but as membership type a supporter is selected raise an error 

if self.membership_type == self.MEMBERSHIP_TYPE_SUPPORTER and self.erfa.has_doppelmitgliedschaft: 

raise ValidationError( 

"Only Members are allowed as Doppelmitglieder") 

 

def _fix_primary_mail(self): 

# make sure we have only one primary email! 

primary_emails = list( 

self.emailaddress_set.filter(is_primary=True).all()) 

for email in primary_emails[1:]: 

logging.warning( 

"Member {} had more than one primary email. We disabled {}". 

format(self.pk, str(email))) 

email.is_primary = False 

email.save() 

if len(primary_emails) == 0: 

email = self.emailaddress_set.first() 

if email: 

logging.warning( 

"Member {} has at least one email, but no primary. We set this email {} to" 

"primary".format(self.pk, str(email))) 

email.is_primary = True 

email.save() 

 

 

class AbstimmungToken(models.Model): 

""" 

A token to print on a Abstimmungs-Karte, which is then being scanned to verify that an Abstimmung is legitimate. 

The token is made of only lower case characters to make it easier to type in case the QR code is unreadable. 

""" 

member = models.OneToOneField( 

Member, 

on_delete=models.CASCADE, 

primary_key=True, 

) 

 

token = models.CharField(max_length=10, 

default=generate_abstimmung_token, 

unique=True, 

null=False, 

blank=False) 

 

abstimmung = models.CharField(max_length=9, 

null=False, 

blank=False) 

 

date_of_count = models.DateField(default=None, null=True) 

 

UNCOUNTED = 'UC' 

COUNTED = 'CO' 

NOT_PAID = 'NP' 

INACTIVE = 'IA' 

EXITED = 'EX' 

NO_RIGHTS = 'NR' 

 

STATUS = ( 

(UNCOUNTED, 'uncounted'), # Has not been validated yet. 

(COUNTED, 'counted'), # Has been positively validated. The rest are reasons for invalidating a vote. 

(NOT_PAID, 'has not paid fees'), 

(INACTIVE, 'inactive'), 

(EXITED, 'exited'), 

(NO_RIGHTS, 'no voting rights'), 

) 

status = models.CharField(max_length=2, choices=STATUS, default=UNCOUNTED, null=False, blank=False) 

 

 

class EmailAddress(DirtyFieldsMixin, models.Model): 

class Meta: 

verbose_name = 'email address' 

verbose_name_plural = 'email addresses' 

unique_together = (('person', 'email_address'), ) 

 

person = models.ForeignKey( 

'Person', on_delete=models.CASCADE 

) # code blaming e.g. ('', related_name='emails') 

email_address = models.EmailField(blank=False, null=False, unique=False) 

is_primary = models.BooleanField(default=False) 

gpg_key_id = models.CharField( 

max_length=60, 

blank=True, 

null=False, 

validators=[ 

RegexValidator( 

regex= 

'^0x[a-fA-F0-9]{8}$|^0x[a-fA-F0-9]{16}$|^[a-fA-F0-9]{40}$', 

message='Enter a valid short or long ID or Fingerprint') 

]) 

 

gpg_error = models.CharField(max_length=256, blank=True, null=False) 

last_update = models.DateField(auto_now=True) 

 

# This field should not be editable 

read_only = (gpg_error, ) 

 

def save(self, *args, **kwargs): 

# Make sure there is always exactly one primary email address. Either this one is going to be it, then set this 

# attribute to false on all other EmailAddress objects, or make this one primary, if otherwise none would be. 

if self.is_primary: 

addresses = EmailAddress.objects.filter(person=self.person) 

if self.pk: 

addresses = addresses.exclude(pk=self.pk) 

addresses.update(is_primary=False) 

elif not EmailAddress.objects.filter(person=self.person, 

is_primary=True).exists(): 

self.is_primary = True 

 

super().save(*args, **kwargs) 

 

def delete(self, *args, **kwargs): 

super().delete(*args, **kwargs) 

 

member_email_addresses = EmailAddress.objects.filter( 

person=self.person) 

681 ↛ exitline 681 didn't return from function 'delete', because the condition on line 681 was never false if member_email_addresses.exists(): 

682 ↛ exitline 682 didn't return from function 'delete', because the condition on line 682 was never false if not member_email_addresses.filter(is_primary=True).exists(): 

new_primary_email_address = member_email_addresses.order_by( 

'-gpg_key_id').first() 

new_primary_email_address.is_primary = True 

new_primary_email_address.save() 

 

def __str__(self): 

return '{} (PGP: {})'.format(self.email_address, ' '.join(textwrap.wrap(self.gpg_key_id, 4)) 

or 'none') 

 

 

class TemplateError(Exception): 

pass 

 

 

class EmailToMember(models.Model): 

class Meta: 

verbose_name_plural = "emails to send" 

 

SEND_TYPE_DEFAULT = 'def' 

SEND_TYPE_DATA_RECORD = 'dml' 

SEND_TYPE_WELCOME = 'wlc' 

SEND_TYPE_DELAYED_PAYMENT = 'dep' 

SEND_TYPE_GPG_ERROR = 'gpg' 

SEND_TYPE_EXIT = 'ext' 

SEND_TYPE_DOPPELERFA_EXIT = 'dex' 

SEND_TYPE_REACTIVATION_REMINDER = 'rar' 

SEND_TYPE_GA_INVITATION = 'gai' 

SEND_TYPE_HAND_MATCHED = 'hdm' 

EMAIL_TO_SEND_TYPES = ( 

(SEND_TYPE_DEFAULT, 'default'), 

(SEND_TYPE_DATA_RECORD, 'data record'), 

(SEND_TYPE_WELCOME, 'welcome'), 

(SEND_TYPE_DELAYED_PAYMENT, 'delayed payment'), 

(SEND_TYPE_GPG_ERROR, 'gpg error'), 

(SEND_TYPE_EXIT, 'member exit'), 

(SEND_TYPE_DOPPELERFA_EXIT, 'doppelerfa exit'), 

(SEND_TYPE_REACTIVATION_REMINDER, 'reactivation reminder'), 

(SEND_TYPE_GA_INVITATION, 'ga invitation'), 

(SEND_TYPE_HAND_MATCHED, 'hand matched payment'), 

) 

 

member = models.ForeignKey( 

Member, on_delete=models.PROTECT 

) # Don't delete a member we still need to send a msg to 

subject = models.CharField(max_length=255, null=False, blank=True) 

body = models.TextField(null=False, blank=True) 

created = models.DateTimeField(auto_now_add=True) 

email_type = models.CharField(max_length=3, 

choices=EMAIL_TO_SEND_TYPES, 

default=SEND_TYPE_DEFAULT) 

 

@staticmethod 

def _render_template(template_name, country_code, context): 

""" 

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

 

:param template_name: The part of the mail template file name between 'mail' and the country code. 

: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. 

""" 

def _get_node(template, name, block_lookups={}): 

""" 

Get a named node from a template. 

Returns `None` if a node with the given name does not exist. 

taken from https://github.com/bradwhittington/django-templated-email/blob/master/templated_email/utils.py 

""" 

context = Context() 

context.template = template 

 

754 ↛ 767line 754 didn't jump to line 767, because the loop on line 754 didn't complete for node in template: 

if isinstance(node, BlockNode) and node.name == name: 

for i in range(len(node.nodelist)): 

n = node.nodelist[i] 

758 ↛ 760line 758 didn't jump to line 760, because the condition on line 758 was never true if isinstance(n, 

BlockNode) and n.name in block_lookups: 

node.nodelist[i] = block_lookups[n.name] 

return node 

762 ↛ 763line 762 didn't jump to line 763, because the condition on line 762 was never true elif isinstance(node, ExtendsNode): 

lookups = dict([(n.name, n) for n in node.nodelist 

if isinstance(n, BlockNode)]) 

lookups.update(block_lookups) 

return _get_node(node.get_parent(context), name, lookups) 

return None 

 

template_paths = [ 

'mail_templates/mail_{}_{}.html'.format(template_name, country) 

for country in [country_code, 'EN'] 

] 

 

template = loader.select_template(template_paths).template 

context.template = template 

 

node_subject = _get_node(template, 'subject') 

node_body = _get_node(template, 'body') 

 

try: 

return node_subject.render(context), node_body.render(context) 

except KeyError as ke: 

raise TemplateError( 

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

 

def rendered_preview(self): 

""" 

A preview with the template's HTML rendered. Suitable for displaying the email in a browser. 

:return: Subject and body enclosed in <pre>-tags. String is safely encoded. 

""" 

from django.utils import safestring 

return safestring.mark_safe('<pre>{}</pre><pre>{}</pre>'.format( 

self.subject, self.body)) 

 

def render_subject_and_body(self): 

(self.subject, self.body) = self._render_template( 

self.get_email_type_display().replace(' ', '_'), 

self.member.address_country, Context({'member': self.member})) 

 

def save(self, *args, **kwargs): 

if not self.pk: # object is being created, thus no primary key field yet 

self.render_subject_and_body() 

super(EmailToMember, self).save(*args, **kwargs) 

 

def send(self, tst=False): 

# First try the primary email address. Then try the addresses with a gpg key, if there are any. Last try 

# sending unencrypted 

email_addresses = self.member.get_emails() 

 

# If any email address has a gpg key id we will only send encrypted emails (or gpg error notifications) 

prefers_encrypted_email = self.member.get_emails().exclude( 

gpg_key_id='').exists() 

 

logging.info('Sending email for {}'.format(self.member.get_name())) 

# Important: The following assumes, that email_adresses are preordered, with all addresses that have 

# non-empty Key IDs at the head of the list. 

sent_mails = [] 

for email_address in email_addresses: 

logging.info(' Trying email address {}'.format(email_address)) 

if email_address.gpg_key_id != '': 

logging.info(' Using gpg key {}'.format( 

email_address.gpg_key_id)) 

recipient_key = PublicKey(email_address.gpg_key_id) 

recipient_key.refresh() # Force-Check Keyservers 

if recipient_key.keystatus == KS.AVLBL: 

if email_address.gpg_key_id.startswith( 

'0x') and recipient_key.key.fpr: 

email_address.gpg_key_id = recipient_key.key.fpr 

email_address.save() 

try: 

attachments = [] 

encrypted_body, result, sign_result = recipient_key.encrypt_to( 

self.body, settings.GPG_HOST_USER) 

834 ↛ 835line 834 didn't jump to line 835, because the condition on line 834 was never true if self.email_type == self.SEND_TYPE_GA_INVITATION: 

try: 

with open('beilagen.pdf', 'rb') as attachment: 

encrypted_attachment, result, sign_result = recipient_key.encrypt_to( 

attachment.read(), 

settings.GPG_HOST_USER) 

attachments.append( 

('beilagen.pdf.asc', 

encrypted_attachment.decode('utf-8'), 

'application/pdf')) 

except IOError: 

pass 

logging.info(' Mailing to: {}'.format( 

email_address.email_address)) 

logging.info(' Encryption result: {}'.format(result)) 

logging.info( 

' Signature result: {}'.format(sign_result)) 

email_address.gpg_error = '' 

sent_mails.append( 

self._send_mail([email_address.email_address], 

self.subject, 

encrypted_body.decode('utf-8'), 

attachments)) 

break 

except Exception as ex: 

# TODO: introduce appropriate logging or an actionable error message here. 

# At this point we have a valid, non-expired, non-revoked key in the keyring 

# so if encryption fails, the problem is with message or signing key. The member cannot 

# control either, so sending an eMail with an error message doesn't help. 

# 

# Also, there's probably no point in continuing here at all. 

logging.error('GPGME Exception: {}'.format(ex)) 

continue 

else: 

email_address.gpg_error = recipient_key.get_error_msg() 

email_address.save() 

 

if recipient_key.refresh_status != KRS.SRVERR: 

# Don't send GPG Error message if the reason for the missing key might be unreachable servers 

# If an unrevoked and unexpired key is available, it will have been used, and this block 

# will not be reached. 

logging.warning( 

' Sending GPG error message email: {}'.format( 

email_address.gpg_error)) 

 

# GPG error notifications will always be sent unencrypted 

(error_subject, error_body) = self._render_template( 

dict(self.EMAIL_TO_SEND_TYPES)[ 

self.SEND_TYPE_GPG_ERROR].replace(' ', '_'), 

self.member.address_country, 

Context({ 

'member': self.member, 

'gpg_error': email_address.gpg_error, 

'email_address': email_address 

})) 

signed_body, sign_result = sign_message( 

error_body, settings.GPG_HOST_USER) 

logging.info( 

' Signature result of GPG error message email: {}'. 

format(sign_result)) 

sent_mails.append( 

self._send_mail([email_address.email_address], 

error_subject, 

signed_body.decode('utf-8'), [], 

False)) 

elif prefers_encrypted_email: 

logging.warning( 

' Failed on all encryptable email addresses for member {}'. 

format(self.member.get_name())) 

else: 

logging.info( 

' Sending unencrypted email to {}'.format(email_address)) 

signed_body, result = sign_message(self.body, 

settings.GPG_HOST_USER) 

attachments = [] 

909 ↛ 910line 909 didn't jump to line 910, because the condition on line 909 was never true if self.email_type == self.SEND_TYPE_GA_INVITATION: 

try: 

with open('beilagen.pdf', 'rb') as attachment: 

attachments.append( 

('beilagen.pdf', attachment.read(), 

'application/pdf')) 

except IOError: 

pass 

sent_mails.append( 

self._send_mail([email_address.email_address], 

self.subject, signed_body.decode('utf-8'), 

attachments)) 

break 

 

# For testing, return all sent mails, otherwise return last mail or the default return 

# value if mails couldn't be sent. 

if tst: 

return sent_mails 

else: 

if sent_mails != []: 

return sent_mails[-1] 

 

return {"mailTo": [], "send_state": 0} 

 

 

def _send_mail(self, 

address, 

subject, 

body, 

attachments=[], 

should_archive=True): 

message_number = _unique_delivery_number() 

local, _, domain = settings.EMAIL_VERP_SENDER.rpartition('@') 

send_email = EmailMessage( 

subject=subject, 

body=body, 

from_email=f'{local}+{message_number}@{domain}', 

headers={'From': settings.EMAIL_SENDER}, 

to=address, 

bcc=[ 

settings.EMAIL_HOST_USER, 

], 

attachments=attachments, 

) 

try: 

send_state = send_email.send(False) 

except ConnectionRefusedError as e: 

logging.error('Sending mail to {} failed with: {}'.format( 

address, e)) 

return {'mailTo': address, 'send_state': 0} 

if send_state > 0 and should_archive: 

self._archive(address, message_number) 

return {'mailTo': address, 'send_state': send_state} 

 

def _archive(self, email_address, message_number): 

mail_archive = ArchivedEmail() 

mail_archive.created_date = self.created 

mail_archive.sent_date = datetime.datetime.now() 

mail_archive.email_type = self.email_type 

mail_archive.member = self.member 

mail_archive.body = self.body 

mail_archive.subject = self.subject 

mail_archive.email_address = str(email_address) 

mail_archive.save() 

self.delete() 

 

def __str__(self): 

return ", ".join([self.subject, str(self.member)]) 

 

 

def _unique_delivery_number(): 

while True: 

alphabet = 'ACDEFHKLMNPRWX39' 

ds_number = 'D' + get_random_string(7, alphabet) 

983 ↛ 981line 983 didn't jump to line 981, because the condition on line 983 was never false if not DeliveryNumber.objects.filter(number=ds_number).exists(): 

return ds_number 

 

 

class ArchivedEmail(models.Model): 

email_address = models.CharField(max_length=255, null=False, blank=True) 

email_type = models.CharField(max_length=3, null=True, default=None) 

member = models.ForeignKey('Member', null=True, on_delete=models.SET_NULL) 

subject = models.CharField(max_length=255, null=False, blank=True) 

body = models.TextField(null=False, blank=True) 

# code blaming: time stamp model inheritance 

created_date = models.DateTimeField(null=False) 

sent_date = models.DateTimeField(auto_now=True) 

 

 

class BalanceTransactionLog(models.Model): 

 

# note currently executing and not just logging, could maybe refactor so actual transaction execution 

# was part of Member and then call this as an actual log 

IMPORT_INITIAL = 'SYN' 

IMPORT_BANKING = 'BAI' 

BILLING_CYCLE = 'BIC' 

MANUAL_BOOKING = 'MAN' 

ACCOUNT_CLOSED = 'ACK' 

NO_INFO = 'NOI' 

 

member = models.ForeignKey('Member', null=True, on_delete=models.SET_NULL) 

changed_value = models.IntegerField(blank=False, null=False) 

new_value = models.IntegerField(blank=False, null=False) 

TRANSACTION_REASON_CHOICES = ( 

(MANUAL_BOOKING, 'MANUAL BOOKING'), 

(IMPORT_INITIAL, 'INITIAL IMPORT'), 

(IMPORT_BANKING, 'BANKING IMPORT'), 

(BILLING_CYCLE, 'BILLING CYCLE'), 

(ACCOUNT_CLOSED, 'ACCOUNT CLOSED'), 

(NO_INFO, 'NO INFORMATION'), 

) 

transaction_reason = models.CharField(max_length=3, 

choices=TRANSACTION_REASON_CHOICES) 

comment = models.CharField(blank=True, null=True, max_length=512) 

created_on = models.DateTimeField(auto_now_add=True) 

booking_day = models.DateField(blank=False, 

null=False, 

default=datetime.date.today) 

bank_transaction = models.OneToOneField('import_app.Transaction', 

null=True, 

on_delete=models.SET_NULL) 

 

def __str__(self): 

return "{}, Amount {}, Balance {}, {}, {}, Timestamp: {}".format( 

self.member, self.changed_value, self.new_value, 

self.transaction_reason, self.comment, self.created_on) 

 

def save_log(self, 

member, 

amount, 

new_value, 

reason=None, 

comment='', 

booking_day=None, 

bank_transaction=None): 

 

if reason is None: 

reason = self.NO_INFO 

self.member = member 

self.comment = comment 

self.transaction_reason = reason 

self.changed_value = amount 

self.new_value = new_value 

if booking_day: 

self.booking_day = booking_day 

self.bank_transaction = bank_transaction 

self.save() 

 

def save(self, *args, **kwargs): 

member = self.member 

defacto_increased_by = member.account_balance - member._original_state[ 

'account_balance'] 

# make sure for new logs that they match changes in active member objects 

1062 ↛ 1063line 1062 didn't jump to line 1063, because the condition on line 1062 was never true if self.pk is None and self.changed_value != defacto_increased_by: 

raise LoggingConsistencyError( 

"balance change ({}) does not match ".format( 

self.changed_value) + 

"actual change in balance ({}) since loading".format( 

defacto_increased_by)) 

super().save() 

 

 

class PremiumAddressLabel(models.Model): 

BASIS = 'BA' 

REPORT = 'RP' 

PLUS = 'PL' 

FOKUS = 'FO' 

HYBRID = 'HY' 

RETOURE = 'RE' 

RETOURE_EXTRA = 'RX' 

PRODUCT_CHOICES = ( 

(BASIS, 'Basis'), 

(REPORT, 'Report'), 

(PLUS, 'Plus'), 

(FOKUS, 'Fokus'), 

(HYBRID, 'Hybrid'), 

(RETOURE, 'Retoure'), 

(RETOURE_EXTRA, 'Retoure Extra'), 

) 

 

name = models.CharField(blank=False, null=False, max_length=100) 

label = models.ImageField() 

pa_id = models.PositiveIntegerField(blank=False, null=False) 

product = models.CharField(max_length=2, 

choices=PRODUCT_CHOICES, 

default=BASIS) 

return_address = models.TextField(blank=False, null=False) 

 

def __str__(self): 

return self.name 

 

 

class DeliveryNumber(models.Model): 

""" 

This number is used to track the delivery of Datenschleudern. It is printed on the address label instead of the 

chaos number for privacy reasons. 

""" 

number = models.CharField(max_length=8, 

unique=True, 

default=_unique_delivery_number, 

blank=False, 

null=False) 

recipient = models.ForeignKey(Person, on_delete=models.CASCADE) 

shipment = models.CharField(max_length=100, blank=False, null=False) 

returned = models.BooleanField(blank=False, null=False, default=False) 

 

def __str__(self): 

return self.number 

 

 

class LoggingConsistencyError(Exception): 

pass 

 

 

def send_or_refresh_data_record(member): 

""" 

This will queue an data record email for the specified Member or refresh any already queued data record email. 

:param member: An instance of a Member object, of whom the data record will be sent. 

:return: None 

""" 

# This should only ever yield zero or one emails. But just in case we handle it like it could be any number. 

emails_in_queue = EmailToMember.objects.filter( 

Q(email_type=EmailToMember.SEND_TYPE_WELCOME) 

| Q(email_type=EmailToMember.SEND_TYPE_DATA_RECORD), 

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_DATA_RECORD, 

member=member).save() 

 

 

def delete_obsolete_payment_reminder(member): 

""" 

If a member paid their fees remove any payment reminder in the message queue 

:param member: An instance of a Member object, of whom the payment reminder will be checked for deletion 

:return: None 

""" 

 

if member.account_balance >= 0: 

 

# This should only ever yield zero or one emails. But just in case we handle it like it could be any number. 

emails_in_queue = EmailToMember.objects.filter( 

email_type=EmailToMember.SEND_TYPE_DELAYED_PAYMENT, member=member) 

 

1157 ↛ 1158line 1157 didn't jump to line 1158, because the loop on line 1157 never started for email in emails_in_queue: 

email.delete() 

 

 

def send_mail_on_member_modification(sender, instance, created, **kwargs): 

"""All logic for sending emails on modifications of a member in one place. Using a signal makes sure that no matter 

which part of the object is modified and from which part inside the code the modification is done, this will always 

be called.""" 

# If a new Member is created create a welcome email 

# If a Member or EmailAddress is modified or an EmailAddress created, then check if either a welcome or data record 

# email exist. If none exists create a data record email and otherwise re-render subject and body to reflect the 

# most recently stored data. 

# Only do anything if any field of interest has been changed. 

1170 ↛ 1172line 1170 didn't jump to line 1172, because the condition on line 1170 was never true if getattr(instance, '_imported', False): 

# No emails for imported Members/EmailAddresses 

return 

elif sender.__name__ == 'Member': 

member = instance 

if created: 

if not member.is_active or member.erfa.has_doppelmitgliedschaft: 

return 

EmailToMember(email_type=EmailToMember.SEND_TYPE_WELCOME, 

member=member).save() 

return 

 

1182 ↛ 1184line 1182 didn't jump to line 1184, because the condition on line 1182 was never true if 'membership_end' in member.get_dirty_fields( 

) and not member.erfa.has_doppelmitgliedschaft: 

EmailToMember(email_type=EmailToMember.SEND_TYPE_EXIT, 

member=member).save() 

 

# When a member is exiting a Doppelmitgliedschaft, then an email is due 

erfa_id = member._original_state['erfa'] 

1189 ↛ 1198line 1189 didn't jump to line 1198, because the condition on line 1189 was never false if erfa_id is not None: 

1190 ↛ 1193line 1190 didn't jump to line 1193, because the condition on line 1190 was never true if Erfa.objects.get( 

pk=erfa_id 

).has_doppelmitgliedschaft and not member.erfa.has_doppelmitgliedschaft: 

EmailToMember( 

email_type=EmailToMember.SEND_TYPE_DOPPELERFA_EXIT, 

member=member).save() 

return 

 

if not any(field in [ 

'first_name', 'last_name', 'address_1', 'address_2', 

'address_3', 'address_country', 'address_unknown', 'comment', 

'erfa', 'fee_last_paid', 'fee_override', 'fee_paid_until', 

'account_balance', 'membership_reduced', 'membership_type' 

] for field in member.get_dirty_fields(check_relationship=True)): 

return 

elif sender.__name__ == 'EmailAddress': 

if any(field in ['email_address', 'gpg_key_id'] 

for field in instance.get_dirty_fields()): 

member = instance.person 

else: 

return 

else: 

return 

 

# For a good measure check if a payment is due every time a member is modified 

# This will call save() again, causing a short loop until the paid until date is in the future 

# ToDo: think about how this is done best 

# member.execute_payment_if_due() 

 

1219 ↛ 1220line 1219 didn't jump to line 1220, because the condition on line 1219 was never true if not member.is_active or member.erfa.has_doppelmitgliedschaft: 

return 

 

send_or_refresh_data_record(member) 

delete_obsolete_payment_reminder(member) 

 

 

post_save.connect(send_mail_on_member_modification)