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

# -*- coding: UTF-8 -*- 

# Copyright 2009-2015 Luc Saffre 

# License: BSD (see file COPYING for details) 

"""Defines the model mixins :class:`Sequenced` and 

:class:`Hierarchical`. 

 

A `Sequenced` is something which has a sequence number and thus a sort 

order which can be manipulated by the user using actions 

:class:`MoveUp` and :class:`MoveDown`. 

 

:class:`Hierarchical` is a :class:`Sequenced` with a `parent` field. 

 

.. autosummary:: 

 

""" 

 

from __future__ import unicode_literals 

from builtins import str 

from builtins import object 

 

import logging 

logger = logging.getLogger(__name__) 

 

from django.db import models 

from django.utils.translation import ugettext_lazy as _ 

from django.core.exceptions import ValidationError 

 

 

from lino.core import actions 

from lino.core import fields 

from lino.core.utils import navinfo 

from lino.utils.xmlgen.html import E 

from lino.utils import AttrDict 

 

from .duplicable import Duplicable, Duplicate 

 

 

class MoveUp(actions.Action): 

    """Move current row one upwards. This action is available on any 

:class:`Sequenced` object as :attr:`Sequenced.move_up`. 

 

    """ 

 

    # label = _("Up") 

    # label = "\u2191" thin arrow up 

    # label = "\u25b2" # triangular arrow up 

    label = "\u25B2"  # ▲ Black up-pointing triangle 

    # label = "↑"  # 

    custom_handler = True 

    # icon_name = 'arrow_up' 

    #~ icon_file = 'arrow_up.png' 

    help_text = _("Move this row one row upwards") 

    readonly = False 

 

    def get_action_permission(self, ar, obj, state): 

        if ar.data_iterator is None: 

            return False 

        if not super(MoveUp, self).get_action_permission(ar, obj, state): 

            return False 

        #~ logger.info("20130927 %r", ar.data_iterator.__class__) 

        if ar.data_iterator.count() == 0: 

            return False 

        if ar.data_iterator[0] == obj: 

            return False 

        return True 

 

    def run_from_ui(self, ar, **kw): 

        obj = ar.selected_rows[0] 

        obj.swap_seqno(ar, -1) 

        #~ obj.move_up() 

        kw = dict() 

        #~ kw.update(refresh=True) 

        kw.update(refresh_all=True) 

        kw.update(message=_("Moved up.")) 

        ar.success(**kw) 

 

 

class MoveDown(actions.Action): 

    """Move current row one downwards. This action is available on any 

:class:`Sequenced` object as :attr:`Sequenced.move_down`. 

 

    """ 

    # label = _("Down") 

    label = "↓" 

    # label = "\u25bc" # triangular arrow down 

    # label = "\u2193" 

    label = "\u25BC"  # ▼ Black down-pointing triangle 

    # icon_name = 'arrow_down' 

    custom_handler = True 

    #~ icon_file = 'arrow_down.png' 

    help_text = _("Move this row one row downwards") 

    readonly = False 

 

    def get_action_permission(self, ar, obj, state): 

        if ar.data_iterator is None: 

            return False 

        if not super(MoveDown, self).get_action_permission(ar, obj, state): 

            return False 

        if ar.data_iterator.count() == 0: 

            return False 

        if ar.data_iterator[ar.data_iterator.count() - 1] == obj: 

            return False 

        #~ if obj.__class__.__name__=='Entry' and obj.seqno == 25: 

            #~ print 20130706, ar.data_iterator.count(), ar.data_iterator 

        return True 

 

    def run_from_ui(self, ar, **kw): 

        obj = ar.selected_rows[0] 

        obj.swap_seqno(ar, 1) 

        #~ obj.move_down() 

        kw = dict() 

        #~ kw.update(refresh=True) 

        kw.update(refresh_all=True) 

        kw.update(message=_("Moved down.")) 

        ar.success(**kw) 

 

 

class DuplicateSequenced(Duplicate): 

    """Duplicate this row.""" 

    def run_from_code(self, ar, **kw): 

        obj = ar.selected_rows[0] 

 

        #~ print '20120605 duplicate', self.seqno, self.account 

        seqno = obj.seqno 

        qs = obj.get_siblings().filter(seqno__gte=seqno).reverse() 

        if qs is None: 

            raise Exception( 

                "20121227 TODO: Tried to duplicate a root element?") 

        for s in qs: 

            #~ print '20120605 duplicate inc', s.seqno, s.account 

            s.seqno += 1 

            s.save() 

        kw.update(seqno=seqno) 

        return super(DuplicateSequenced, self).run_from_code(ar, **kw) 

 

 

from django.utils.encoding import python_2_unicode_compatible 

 

 

@python_2_unicode_compatible 

class Sequenced(Duplicable): 

    """Mixin for models that have a field :attr:`seqno` containing a 

    "sequence number". 

 

    .. attribute:: seqno 

 

        The sequence number of this item with its parent. 

 

    .. method:: duplicate 

 

        Create a duplicate of this object and insert the new object 

        below this one. 

 

    .. attribute:: move_up 

 

        Exchange the :attr:`seqno` of this item and the previous item. 

 

    .. attribute:: move_down 

 

        Exchange the :attr:`seqno` of this item and the next item. 

 

    .. attribute:: move_buttons 

 

        Displays buttons for certain actions on this row: 

 

        - :attr:`move_up` and :attr:`move_down` 

        - duplicate 

 

    """ 

 

    class Meta(object): 

        abstract = True 

        ordering = ['seqno'] 

 

    seqno = models.IntegerField(_("Seq.No."), blank=True, null=False) 

 

    duplicate = DuplicateSequenced() 

    """The :class:`DuplicateSequenced` action for this object. 

 

    """ 

 

    move_up = MoveUp() 

    """The :class:`MoveUp` action on this object. 

 

    """ 

 

    move_down = MoveDown() 

    """The :class:`MoveDown` action on this object. 

 

    """ 

 

    def __str__(self): 

        return str(_("Row # %s") % self.seqno) 

 

    def get_siblings(self): 

        """Return a Django Queryset with all siblings of this, 

        or `None` if this is a root element which cannot have any siblings. 

 

        Siblings are all objects that belong to a same sequence. 

        This is needed for automatic management of the `seqno` field. 

 

        The queryset will of course include `self`. 

        The default implementation uses a global sequencing 

        by returning all objects of `self`'s model. 

 

        A common case for overriding this method is when numbering 

        restarts for each master.  For example if you have a master 

        model `Product` and a sequenced slave model `Property` with a 

        ForeignKey field `product` which points to the Product, then 

        you'll define:: 

 

          class Property(dd.Sequenced): 

 

              def get_siblings(self): 

                  return Property.objects.filter( 

                      product=self.product).order_by('seqno') 

 

        Overridden e.g. in 

        :class:`lino_xl.lib.thirds.models.Third` 

        or 

        :class:`lino_welfare.modlib.debts.models.Entry`. 

 

        """ 

        return self.__class__.objects.order_by('seqno') 

 

    def set_seqno(self): 

        """ 

        Initialize `seqno` to the `seqno` of eldest sibling + 1. 

        """ 

        qs = self.get_siblings() 

        if qs is None: 

            self.seqno = 0 

        else: 

            n = qs.count() 

            if n == 0: 

                self.seqno = 1 

            else: 

                last = qs[n - 1] 

                self.seqno = last.seqno + 1 

 

    def full_clean(self, *args, **kw): 

        if self.seqno is None: 

            self.set_seqno() 

        # if hasattr(self, 'amount'): 

        #     logger.info("20151117 Sequenced.full_clean a %s", self.amount) 

        #     logger.info("20151117  %s", self.__class__.mro()) 

        super(Sequenced, self).full_clean(*args, **kw) 

        # if hasattr(self, 'amount'): 

        #     logger.info("20151117 Sequenced.full_clean b %s", self.amount) 

 

    def swap_seqno(self, ar, offset): 

        """ 

        Move this row "up or down" within its siblings 

        """ 

        #~ qs = self.get_siblings() 

        qs = ar.data_iterator 

        if qs is None: 

            return 

        nav = AttrDict(**navinfo(qs, self)) 

        if not nav.recno: 

            return 

        new_recno = nav.recno + offset 

        if new_recno <= 0: 

            return 

        if new_recno > qs.count(): 

            return 

        other = qs[new_recno - 1] 

        prev_seqno = other.seqno 

        other.seqno = self.seqno 

        self.seqno = prev_seqno 

        self.save() 

        other.save() 

 

    @fields.displayfield(_("Move")) 

    def move_buttons(obj, ar): 

        if ar is None: 

            return '' 

        actor = ar.actor 

        l = [] 

        state = None  # TODO: support a possible state? 

        for n in ('move_up', 'move_down', 'duplicate'): 

            ba = actor.get_action_by_name(n) 

            if ba.get_row_permission(ar, obj, state): 

                l.append(ar.renderer.action_button(obj, ar, ba)) 

                l.append(' ') 

        return E.p(*l) 

 

 

Sequenced.set_widget_options('move_buttons', width=5) 

 

 

class Hierarchical(Duplicable): 

    """Abstract model mixin for things that have a "parent" and 

    "siblings". 

 

    """ 

    class Meta(object): 

        abstract = True 

 

    parent = models.ForeignKey('self', 

                               verbose_name=_("Parent"), 

                               null=True, blank=True, 

                               related_name='children') 

 

    def get_siblings(self): 

        if self.parent: 

            return self.parent.children.all() 

        return self.__class__.objects.filter(parent__isnull=True) 

 

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

        #~ super(Hierarchical, self).save(*args, **kwargs) 

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

        p = self.parent 

        while p is not None: 

            if p == self: 

                raise ValidationError("Cannot be your own ancestor") 

            p = p.parent 

        super(Hierarchical, self).full_clean(*args, **kwargs) 

 

    def is_parented(self, other): 

        if self == other: 

            return True 

        p = self.parent 

        while p is not None: 

            if p == other: 

                return True 

            p = p.parent 

 

    def get_parents(self): 

        rv = [] 

        p = self.parent 

        while p is not None: 

            rv.insert(p) 

            p = p.parent 

        return rv 

 

    def get_parental_line(self): 

        """A top-level project is its own root.""" 

        obj = self 

        tree = [obj] 

        while obj.parent is not None: 

            obj = obj.parent 

            if obj in tree: 

                raise Exception("Circular parent") 

            tree.insert(0, obj) 

        return tree 

 

    def whole_clan(self): 

        # TODO: go deeper but check for circular references 

        clan = set([self]) 

        l1 = self.__class__.objects.filter(parent=self) 

        if l1.count() == 0: 

            return clan 

        clan |= set(l1) 

        l2 = self.__class__.objects.filter(parent__in=l1) 

        if l2.count() == 0: 

            return clan 

        clan |= set(l2) 

        l3 = self.__class__.objects.filter(parent__in=l2) 

        if l3.count() == 0: 

            return clan 

        clan |= set(l3) 

        # print 20150421, projects 

        return clan