source: rattail/rattail/batch/purchase.py @ 0b88942

Last change on this file since 0b88942 was 0b88942, checked in by Lance Edgar <ledgar@…>, 6 months ago

Update receiving batch logic to leverage new truck_dump_status

missed some things in recent commit(s)...

  • Property mode set to 100644
File size: 90.2 KB
Line 
1# -*- coding: utf-8; -*-
2################################################################################
3#
4#  Rattail -- Retail Software Framework
5#  Copyright © 2010-2019 Lance Edgar
6#
7#  This file is part of Rattail.
8#
9#  Rattail is free software: you can redistribute it and/or modify it under the
10#  terms of the GNU General Public License as published by the Free Software
11#  Foundation, either version 3 of the License, or (at your option) any later
12#  version.
13#
14#  Rattail is distributed in the hope that it will be useful, but WITHOUT ANY
15#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16#  FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17#  details.
18#
19#  You should have received a copy of the GNU General Public License along with
20#  Rattail.  If not, see <http://www.gnu.org/licenses/>.
21#
22################################################################################
23"""
24Handler for purchase order batches
25"""
26
27from __future__ import unicode_literals, absolute_import, division
28
29import logging
30
31import six
32from sqlalchemy import orm
33
34from rattail.db import model, api
35from rattail.gpc import GPC
36from rattail.batch import BatchHandler
37from rattail.time import make_utc
38from rattail.vendors.invoices import require_invoice_parser
39
40
41log = logging.getLogger(__name__)
42
43
44class PurchaseBatchHandler(BatchHandler):
45    """
46    Handler for purchase order batches.
47    """
48    batch_model_class = model.PurchaseBatch
49
50    def allow_cases(self):
51        """
52        Must return boolean indicating whether "cases" should be generally
53        allowed, for sake of quantity input etc.
54        """
55        return self.config.getbool('rattail.batch', 'purchase.allow_cases',
56                                   default=True)
57
58    def allow_expired_credits(self):
59        """
60        Must return boolean indicating whether "expired" credits should be
61        tracked.  In practice, this should either en- or dis-able various UI
62        elements which involves expired product.
63        """
64        return self.config.getbool('rattail.batch', 'purchase.allow_expired_credits',
65                                   default=True)
66
67    def should_populate(self, batch):
68        # TODO: this probably should change soon, for now this works..
69        return batch.purchase and batch.mode in (self.enum.PURCHASE_BATCH_MODE_RECEIVING,
70                                                 self.enum.PURCHASE_BATCH_MODE_COSTING)
71
72    def populate(self, batch, progress=None):
73        assert batch.purchase and batch.mode in (self.enum.PURCHASE_BATCH_MODE_RECEIVING,
74                                                 self.enum.PURCHASE_BATCH_MODE_COSTING)
75        batch.order_quantities_known = True
76
77        def append(item, i):
78            row = model.PurchaseBatchRow()
79            product = item.product
80            row.item = item
81            row.product = product
82            if product:
83                row.upc = product.upc
84                row.item_id = product.item_id
85            else:
86                row.upc = item.upc
87                row.item_id = item.item_id
88            row.cases_ordered = item.cases_ordered
89            row.units_ordered = item.units_ordered
90            row.cases_received = item.cases_received
91            row.units_received = item.units_received
92            row.po_unit_cost = item.po_unit_cost
93            row.po_total = item.po_total
94            if batch.mode == self.enum.PURCHASE_BATCH_MODE_COSTING:
95                row.invoice_unit_cost = item.invoice_unit_cost
96                row.invoice_total = item.invoice_total
97            self.add_row(batch, row)
98
99        self.progress_loop(append, batch.purchase.items, progress,
100                           message="Adding initial rows to batch")
101
102        # TODO: should(n't) this be handled elsewhere?
103        session = orm.object_session(batch)
104        session.flush()
105        self.refresh_batch_status(batch)
106
107    def populate_from_truck_dump_invoice(self, batch, progress=None):
108        child_batch = batch
109        parent_batch = child_batch.truck_dump_batch
110        session = orm.object_session(child_batch)
111
112        parser = require_invoice_parser(child_batch.invoice_parser_key)
113        parser.session = session
114
115        parser.vendor = api.get_vendor(session, parser.vendor_key)
116        if parser.vendor is not child_batch.vendor:
117            raise RuntimeError("Parser is for vendor '{}' but batch is for: {}".format(
118                parser.vendor_key, child_batch.vendor))
119
120        path = child_batch.filepath(self.config, child_batch.invoice_file)
121        child_batch.invoice_date = parser.parse_invoice_date(path)
122        child_batch.order_quantities_known = True
123
124        def append(invoice_row, i):
125            row = self.make_row_from_invoice(child_batch, invoice_row)
126            self.add_row(child_batch, row)
127
128        self.progress_loop(append, list(parser.parse_rows(path)), progress,
129                           message="Adding initial rows to batch")
130
131        if parent_batch.truck_dump_children_first:
132            # children first, so should add rows to parent batch now
133            session.flush()
134
135            def append(child_row, i):
136                if not child_row.out_of_stock:
137
138                    # if row for this product already exists in parent, must aggregate
139                    parent_row = self.locate_parent_row_for_child(parent_batch, child_row)
140                    if parent_row:
141
142                        # confirm 'case_quantity' matches
143                        if parent_row.case_quantity != child_row.case_quantity:
144                            raise ValueError("differing 'case_quantity' for item {}: {}".format(
145                                child_row.item_entry, child_row.description))
146
147                        # confirm 'out_of_stock' matches
148                        if parent_row.out_of_stock != child_row.out_of_stock:
149                            raise ValueError("differing 'out_of_stock' for item {}: {}".format(
150                                cihld_row.item_entry, child_row.description))
151
152                        # confirm 'invoice_unit_cost' matches
153                        if parent_row.invoice_unit_cost != child_row.invoice_unit_cost:
154                            raise ValueError("differing 'invoice_unit_cost' for item {}: {}".format(
155                                cihld_row.item_entry, child_row.description))
156
157                        # confirm 'invoice_case_cost' matches
158                        if parent_row.invoice_case_cost != child_row.invoice_case_cost:
159                            raise ValueError("differing 'invoice_case_cost' for item {}: {}".format(
160                                cihld_row.item_entry, child_row.description))
161
162                        # add 'ordered' quantities
163                        if child_row.cases_ordered:
164                            parent_row.cases_ordered = (parent_row.cases_ordered or 0) + child_row.cases_ordered
165                        if child_row.units_ordered:
166                            parent_row.units_ordered = (parent_row.units_ordered or 0) + child_row.units_ordered
167
168                        # add 'shipped' quantities
169                        if child_row.cases_shipped:
170                            parent_row.cases_shipped = (parent_row.cases_shipped or 0) + child_row.cases_shipped
171                        if child_row.units_shipped:
172                            parent_row.units_shipped = (parent_row.units_shipped or 0) + child_row.units_shipped
173
174                        # add 'invoice_total' quantities
175                        if child_row.invoice_total:
176                            parent_row.invoice_total = (parent_row.invoice_total or 0) + child_row.invoice_total
177
178                    else: # new product; simply add new row to parent
179                        parent_row = self.make_parent_row_from_child(child_row)
180                        self.add_row(parent_batch, parent_row)
181
182            self.progress_loop(append, child_batch.active_rows(), progress,
183                               message="Adding rows to parent batch")
184
185        else: # children last, so should make parent claims now
186            self.make_truck_dump_claims_for_child_batch(child_batch, progress=progress)
187
188        self.refresh_batch_status(parent_batch)
189
190    def locate_parent_row_for_child(self, parent_batch, child_row):
191        """
192        Locate a row within parent batch, which "matches" given row from child
193        batch.  May return ``None`` if no match found.
194        """
195        if child_row.product_uuid:
196            rows = [row for row in parent_batch.active_rows()
197                    if row.product_uuid == child_row.product_uuid]
198            if rows:
199                return rows[0]
200
201        elif child_row.item_entry:
202            rows = [row for row in parent_batch.active_rows()
203                    if row.product_uuid is None
204                    and row.item_entry == child_row.item_entry]
205            if rows:
206                return rows[0]
207
208    def make_row_from_invoice(self, batch, invoice_row):
209        row = model.PurchaseBatchRow()
210        row.item_entry = invoice_row.item_entry
211        row.upc = invoice_row.upc
212        row.vendor_code = invoice_row.vendor_code
213        row.brand_name = invoice_row.brand_name
214        row.description = invoice_row.description
215        row.size = invoice_row.size
216        row.case_quantity = invoice_row.case_quantity
217        row.cases_ordered = invoice_row.ordered_cases
218        row.units_ordered = invoice_row.ordered_units
219        row.cases_shipped = invoice_row.shipped_cases
220        row.units_shipped = invoice_row.shipped_units
221        row.out_of_stock = invoice_row.out_of_stock
222        row.invoice_unit_cost = invoice_row.unit_cost
223        row.invoice_total = invoice_row.total_cost
224        row.invoice_case_cost = invoice_row.case_cost
225        return row
226
227    def make_parent_row_from_child(self, child_row):
228        row = model.PurchaseBatchRow()
229        row.item_entry = child_row.item_entry
230        row.upc = child_row.upc
231        row.vendor_code = child_row.vendor_code
232        row.brand_name = child_row.brand_name
233        row.description = child_row.description
234        row.size = child_row.size
235        row.case_quantity = child_row.case_quantity
236        row.cases_ordered = child_row.cases_ordered
237        row.units_ordered = child_row.units_ordered
238        row.cases_shipped = child_row.cases_shipped
239        row.units_shipped = child_row.units_shipped
240        row.out_of_stock = child_row.out_of_stock
241        row.invoice_unit_cost = child_row.invoice_unit_cost
242        row.invoice_total = child_row.invoice_total
243        row.invoice_case_cost = child_row.invoice_case_cost
244        return row
245
246    def make_truck_dump_claims_for_child_batch(self, batch, progress=None):
247        """
248        Make all "claims" against a truck dump, for the given child batch.
249        This assumes no claims exist for the child batch at time of calling,
250        and that the truck dump batch is complete and not yet executed.
251        """
252        session = orm.object_session(batch)
253        truck_dump_rows = batch.truck_dump_batch.active_rows()
254        child_rows = batch.active_rows()
255
256        # organize truck dump by product and UPC
257        truck_dump_by_product = {}
258        truck_dump_by_upc = {}
259
260        def organize_parent(row, i):
261            if row.product:
262                truck_dump_by_product.setdefault(row.product.uuid, []).append(row)
263            if row.upc:
264                truck_dump_by_upc.setdefault(row.upc, []).append(row)
265
266        self.progress_loop(organize_parent, truck_dump_rows, progress,
267                           message="Organizing truck dump parent rows")
268
269        # organize child batch by product and UPC
270        child_by_product = {}
271        child_by_upc = {}
272
273        def organize_child(row, i):
274            if row.product:
275                child_by_product.setdefault(row.product.uuid, []).append(row)
276            if row.upc:
277                child_by_upc.setdefault(row.upc, []).append(row)
278
279        self.progress_loop(organize_child, child_rows, progress,
280                           message="Organizing truck dump child rows")
281
282        # okay then, let's go through all our organized rows, and make claims
283
284        def make_claims(child_product, i):
285            uuid, child_product_rows = child_product
286            if uuid in truck_dump_by_product:
287                truck_dump_product_rows = truck_dump_by_product[uuid]
288                for truck_dump_row in truck_dump_product_rows:
289                    self.make_truck_dump_claims(truck_dump_row, child_product_rows)
290
291        self.progress_loop(make_claims, child_by_product.items(), progress,
292                           count=len(child_by_product),
293                           message="Claiming parent rows for child") # (pass #1)
294
295    def make_truck_dump_claims(self, truck_dump_row, child_rows):
296
297        # first we go through the truck dump parent row, and calculate all
298        # "present", and "claimed" vs. "pending" product quantities
299
300        # cases_received
301        cases_received = truck_dump_row.cases_received or 0
302        cases_received_claimed = sum([claim.cases_received or 0
303                                      for claim in truck_dump_row.claims])
304        cases_received_pending = cases_received - cases_received_claimed
305
306        # units_received
307        units_received = truck_dump_row.units_received or 0
308        units_received_claimed = sum([claim.units_received or 0
309                                      for claim in truck_dump_row.claims])
310        units_received_pending = units_received - units_received_claimed
311
312        # cases_damaged
313        cases_damaged = truck_dump_row.cases_damaged or 0
314        cases_damaged_claimed = sum([claim.cases_damaged or 0
315                                     for claim in truck_dump_row.claims])
316        cases_damaged_pending = cases_damaged - cases_damaged_claimed
317
318        # units_damaged
319        units_damaged = truck_dump_row.units_damaged or 0
320        units_damaged_claimed = sum([claim.units_damaged or 0
321                                     for claim in truck_dump_row.claims])
322        units_damaged_pending = units_damaged - units_damaged_claimed
323
324        # cases_expired
325        cases_expired = truck_dump_row.cases_expired or 0
326        cases_expired_claimed = sum([claim.cases_expired or 0
327                                     for claim in truck_dump_row.claims])
328        cases_expired_pending = cases_expired - cases_expired_claimed
329
330        # units_expired
331        units_expired = truck_dump_row.units_expired or 0
332        units_expired_claimed = sum([claim.units_expired or 0
333                                     for claim in truck_dump_row.claims])
334        units_expired_pending = units_expired - units_expired_claimed
335
336        # TODO: should be calculating mispicks here too, right?
337
338        def make_claim(child_row):
339            c = model.PurchaseBatchRowClaim()
340            c.claiming_row = child_row
341            truck_dump_row.claims.append(c)
342            return c
343
344        for child_row in child_rows:
345
346            # stop now if everything in this parent row is accounted for
347            if not (cases_received_pending or units_received_pending
348                    or cases_damaged_pending or units_damaged_pending
349                    or cases_expired_pending or units_expired_pending):
350                break
351
352            # for each child row we also calculate all "present", and "claimed"
353            # vs. "pending" product quantities
354
355            # cases_ordered
356            cases_ordered = child_row.cases_ordered or 0
357            cases_ordered_claimed = sum([(claim.cases_received or 0)
358                                         + (claim.cases_damaged or 0)
359                                         + (claim.cases_expired or 0)
360                                         for claim in child_row.truck_dump_claims])
361            cases_ordered_pending = cases_ordered - cases_ordered_claimed
362
363            # units_ordered
364            units_ordered = child_row.units_ordered or 0
365            units_ordered_claimed = sum([(claim.units_received or 0)
366                                         + (claim.units_damaged or 0)
367                                         + (claim.units_expired or 0)
368                                         for claim in child_row.truck_dump_claims])
369            units_ordered_pending = units_ordered - units_ordered_claimed
370
371            # skip this child row if everything in it is accounted for
372            if not (cases_ordered_pending or units_ordered_pending):
373                continue
374
375            # there should only be one claim for this parent/child combo
376            claim = None
377
378            # let's cache this
379            case_quantity = child_row.case_quantity
380
381            # make case claims
382            if cases_ordered_pending and cases_received_pending:
383                claim = claim or make_claim(child_row)
384                if cases_received_pending >= cases_ordered_pending:
385                    claim.cases_received = (claim.cases_received or 0) + cases_ordered_pending
386                    child_row.cases_received = (child_row.cases_received or 0) + cases_ordered_pending
387                    cases_received_pending -= cases_ordered_pending
388                    cases_ordered_pending = 0
389                else: # ordered > received
390                    claim.cases_received = (claim.cases_received or 0) + cases_received_pending
391                    child_row.cases_received = (child_row.cases_received or 0) + cases_received_pending
392                    cases_ordered_pending -= cases_received_pending
393                    cases_received_pending = 0
394                self.refresh_row(child_row)
395            if cases_ordered_pending and cases_damaged_pending:
396                claim = claim or make_claim(child_row)
397                if cases_damaged_pending >= cases_ordered_pending:
398                    claim.cases_damaged = (claim.cases_damaged or 0) + cases_ordered_pending
399                    child_row.cases_damaged = (child_row.cases_damaged or 0) + cases_ordered_pending
400                    cases_damaged_pending -= cases_ordered_pending
401                    cases_ordered_pending = 0
402                else: # ordered > damaged
403                    claim.cases_damaged = (claim.cases_damaged or 0) + cases_damaged_pending
404                    child_row.cases_damaged = (child_row.cases_damaged or 0) + cases_damaged_pending
405                    cases_ordered_pending -= cases_damaged_pending
406                    cases_damaged_pending = 0
407                self.refresh_row(child_row)
408            if cases_ordered_pending and cases_expired_pending:
409                claim = claim or make_claim(child_row)
410                if cases_expired_pending >= cases_ordered_pending:
411                    claim.cases_expired = (claim.cases_expired or 0) + cases_ordered_pending
412                    child_row.cases_expired = (child_row.cases_expired or 0) + cases_ordered_pending
413                    cases_expired_pending -= cases_ordered_pending
414                    cases_ordered_pending = 0
415                else: # ordered > expired
416                    claim.cases_expired = (claim.cases_expired or 0) + cases_expired_pending
417                    child_row.cases_expired = (child_row.cases_expired or 0) + cases_expired_pending
418                    cases_ordered_pending -= cases_expired_pending
419                    cases_expired_pending = 0
420                self.refresh_row(child_row)
421
422            # make unit claims
423            if units_ordered_pending and units_received_pending:
424                claim = claim or make_claim(child_row)
425                if units_received_pending >= units_ordered_pending:
426                    claim.units_received = (claim.units_received or 0) + units_ordered_pending
427                    child_row.units_received = (child_row.units_received or 0) + units_ordered_pending
428                    units_received_pending -= units_ordered_pending
429                    units_ordered_pending = 0
430                else: # ordered > received
431                    claim.units_received = (claim.units_received or 0) + units_received_pending
432                    child_row.units_received = (child_row.units_received or 0) + units_received_pending
433                    units_ordered_pending -= units_received_pending
434                    units_received_pending = 0
435                self.refresh_row(child_row)
436            if units_ordered_pending and units_damaged_pending:
437                claim = claim or make_claim(child_row)
438                if units_damaged_pending >= units_ordered_pending:
439                    claim.units_damaged = (claim.units_damaged or 0) + units_ordered_pending
440                    child_row.units_damaged = (child_row.units_damaged or 0) + units_ordered_pending
441                    units_damaged_pending -= units_ordered_pending
442                    units_ordered_pending = 0
443                else: # ordered > damaged
444                    claim.units_damaged = (claim.units_damaged or 0) + units_damaged_pending
445                    child_row.units_damaged = (child_row.units_damaged or 0) + units_damaged_pending
446                    units_ordered_pending -= units_damaged_pending
447                    units_damaged_pending = 0
448                self.refresh_row(child_row)
449            if units_ordered_pending and units_expired_pending:
450                claim = claim or make_claim(child_row)
451                if units_expired_pending >= units_ordered_pending:
452                    claim.units_expired = (claim.units_expired or 0) + units_ordered_pending
453                    child_row.units_expired = (child_row.units_expired or 0) + units_ordered_pending
454                    units_expired_pending -= units_ordered_pending
455                    units_ordered_pending = 0
456                else: # ordered > expired
457                    claim.units_expired = (claim.units_expired or 0) + units_expired_pending
458                    child_row.units_expired = (child_row.units_expired or 0) + units_expired_pending
459                    units_ordered_pending -= units_expired_pending
460                    units_expired_pending = 0
461                self.refresh_row(child_row)
462
463            # claim units from parent, as cases for child.  note that this
464            # crosses the case/unit boundary, but is considered "safe" because
465            # we assume the child row has correct case quantity even if parent
466            # row has a different one.
467            if cases_ordered_pending and units_received_pending:
468                received = units_received_pending // case_quantity
469                if received:
470                    claim = claim or make_claim(child_row)
471                    if received >= cases_ordered_pending:
472                        claim.cases_received = (claim.cases_received or 0) + cases_ordered_pending
473                        child_row.cases_received = (child_row.units_received or 0) + cases_ordered_pending
474                        units_received_pending -= (cases_ordered_pending * case_quantity)
475                        cases_ordered_pending = 0
476                    else: # ordered > received
477                        claim.cases_received = (claim.cases_received or 0) + received
478                        child_row.cases_received = (child_row.units_received or 0) + received
479                        cases_ordered_pending -= received
480                        units_received_pending -= (received * case_quantity)
481                    self.refresh_row(child_row)
482            if cases_ordered_pending and units_damaged_pending:
483                damaged = units_damaged_pending // case_quantity
484                if damaged:
485                    claim = claim or make_claim(child_row)
486                    if damaged >= cases_ordered_pending:
487                        claim.cases_damaged = (claim.cases_damaged or 0) + cases_ordered_pending
488                        child_row.cases_damaged = (child_row.units_damaged or 0) + cases_ordered_pending
489                        units_damaged_pending -= (cases_ordered_pending * case_quantity)
490                        cases_ordered_pending = 0
491                    else: # ordered > damaged
492                        claim.cases_damaged = (claim.cases_damaged or 0) + damaged
493                        child_row.cases_damaged = (child_row.units_damaged or 0) + damaged
494                        cases_ordered_pending -= damaged
495                        units_damaged_pending -= (damaged * case_quantity)
496                    self.refresh_row(child_row)
497            if cases_ordered_pending and units_expired_pending:
498                expired = units_expired_pending // case_quantity
499                if expired:
500                    claim = claim or make_claim(child_row)
501                    if expired >= cases_ordered_pending:
502                        claim.cases_expired = (claim.cases_expired or 0) + cases_ordered_pending
503                        child_row.cases_expired = (child_row.units_expired or 0) + cases_ordered_pending
504                        units_expired_pending -= (cases_ordered_pending * case_quantity)
505                        cases_ordered_pending = 0
506                    else: # ordered > expired
507                        claim.cases_expired = (claim.cases_expired or 0) + expired
508                        child_row.cases_expired = (child_row.units_expired or 0) + expired
509                        cases_ordered_pending -= expired
510                        units_expired_pending -= (expired * case_quantity)
511                    self.refresh_row(child_row)
512
513            # if necessary, try to claim cases from parent, as units for child.
514            # this also crosses the case/unit boundary but is considered safe
515            # only if the case quantity matches between child and parent rows.
516            # (otherwise who knows what could go wrong.)
517            if case_quantity == truck_dump_row.case_quantity:
518                if units_ordered_pending and cases_received_pending:
519                    received = cases_received_pending * case_quantity
520                    claim = claim or make_claim(child_row)
521                    if received >= units_ordered_pending:
522                        claim.units_received = (claim.units_received or 0) + units_ordered_pending
523                        child_row.units_received = (child_row.units_received or 0) + units_ordered_pending
524                        leftover = received % units_ordered_pending
525                        if leftover == 0:
526                            cases_received_pending -= (received // units_ordered_pending)
527                        else:
528                            cases_received_pending -= (received // units_ordered_pending) - 1
529                            units_received_pending += leftover
530                        units_ordered_pending = 0
531                    else: # ordered > received
532                        claim.units_received = (claim.units_received or 0) + received
533                        child_row.units_received = (child_row.units_received or 0) + received
534                        units_ordered_pending -= received
535                        cases_received_pending = 0
536                    self.refresh_row(child_row)
537                if units_ordered_pending and cases_damaged_pending:
538                    damaged = cases_damaged_pending * case_quantity
539                    claim = claim or make_claim(child_row)
540                    if damaged >= units_ordered_pending:
541                        claim.units_damaged = (claim.units_damaged or 0) + units_ordered_pending
542                        child_row.units_damaged = (child_row.units_damaged or 0) + units_ordered_pending
543                        leftover = damaged % units_ordered_pending
544                        if leftover == 0:
545                            cases_damaged_pending -= (damaged // units_ordered_pending)
546                        else:
547                            cases_damaged_pending -= (damaged // units_ordered_pending) - 1
548                            units_damaged_pending += leftover
549                        units_ordered_pending = 0
550                    else: # ordered > damaged
551                        claim.units_damaged = (claim.units_damaged or 0) + damaged
552                        child_row.units_damaged = (child_row.units_damaged or 0) + damaged
553                        units_ordered_pending -= damaged
554                        cases_damaged_pending = 0
555                    self.refresh_row(child_row)
556                if units_ordered_pending and cases_expired_pending:
557                    expired = cases_expired_pending * case_quantity
558                    claim = claim or make_claim(child_row)
559                    if expired >= units_ordered_pending:
560                        claim.units_expired = (claim.units_expired or 0) + units_ordered_pending
561                        child_row.units_expired = (child_row.units_expired or 0) + units_ordered_pending
562                        leftover = expired % units_ordered_pending
563                        if leftover == 0:
564                            cases_expired_pending -= (expired // units_ordered_pending)
565                        else:
566                            cases_expired_pending -= (expired // units_ordered_pending) - 1
567                            units_expired_pending += leftover
568                        units_ordered_pending = 0
569                    else: # ordered > expired
570                        claim.units_expired = (claim.units_expired or 0) + expired
571                        child_row.units_expired = (child_row.units_expired or 0) + expired
572                        units_ordered_pending -= expired
573                        cases_expired_pending = 0
574                    self.refresh_row(child_row)
575
576            # refresh the parent row, to reflect any new claim(s) made
577            self.refresh_row(truck_dump_row)
578
579    def clone_truck_dump_credit(self, truck_dump_credit, child_row):
580        """
581        Clone a credit record from a truck dump, onto the given child row.
582        """
583        child_batch = child_row.batch
584        child_credit = model.PurchaseBatchCredit()
585        self.copy_credit_attributes(truck_dump_credit, child_credit)
586        child_credit.date_ordered = child_batch.date_ordered
587        child_credit.date_shipped = child_batch.date_shipped
588        child_credit.date_received = child_batch.date_received
589        child_credit.invoice_date = child_batch.invoice_date
590        child_credit.invoice_number = child_batch.invoice_number
591        child_credit.invoice_line_number = child_row.invoice_line_number
592        child_credit.invoice_case_cost = child_row.invoice_case_cost
593        child_credit.invoice_unit_cost = child_row.invoice_unit_cost
594        child_credit.invoice_total = child_row.invoice_total
595        child_row.credits.append(child_credit)
596        return child_credit
597
598    # TODO: surely this should live elsewhere
599    def calc_best_fit(self, units, case_quantity):
600        case_quantity = case_quantity or 1
601        if case_quantity == 1:
602            return 0, units
603        cases = units // case_quantity
604        if cases:
605            return cases, units - (cases * case_quantity)
606        return 0, units
607
608    def refresh(self, batch, progress=None):
609
610        # reset PO total for ordering batch
611        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
612            batch.po_total = 0
613
614        # reset invoice total for receiving and costing batch
615        elif batch.mode in (self.enum.PURCHASE_BATCH_MODE_RECEIVING,
616                            self.enum.PURCHASE_BATCH_MODE_COSTING):
617            batch.invoice_total = 0
618
619        # refresh all rows etc. per usual
620        result = super(PurchaseBatchHandler, self).refresh(batch, progress=progress)
621        if result:
622
623            # here begins some extra magic for truck dump receiving batches
624            if batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
625                session = orm.object_session(batch)
626                session.flush()
627
628                if batch.is_truck_dump_parent():
629
630                    # will try to establish new claims against the parent
631                    # batch, where possible
632                    unclaimed = [row for row in batch.active_rows()
633                                 if row.status_code in (row.STATUS_TRUCKDUMP_UNCLAIMED,
634                                                        row.STATUS_TRUCKDUMP_PARTCLAIMED)]
635                    for row in unclaimed:
636                        if row.product_uuid: # only support rows with product for now
637                            self.make_truck_dump_claims_for_parent_row(row)
638
639                    # all rows should be refreshed now, but batch status still needs it
640                    self.refresh_batch_status(batch)
641                    for child in batch.truck_dump_children:
642                        self.refresh_batch_status(child)
643
644                elif batch.is_truck_dump_child():
645
646                    # will try to establish claims against the parent batch,
647                    # for each "incomplete" row (i.e. those with unclaimed
648                    # order quantities)
649                    incomplete = [row for row in batch.active_rows()
650                                  if row.status_code in (row.STATUS_INCOMPLETE,
651                                                         row.STATUS_ORDERED_RECEIVED_DIFFER)]
652                    for row in incomplete:
653                        if row.product_uuid: # only support rows with product for now
654                            parent_rows = [parent_row for parent_row in batch.truck_dump_batch.active_rows()
655                                           if parent_row.product_uuid == row.product_uuid]
656                            for parent_row in parent_rows:
657                                self.make_truck_dump_claims(parent_row, [row])
658                                if row.status_code not in (row.STATUS_INCOMPLETE,
659                                                           row.STATUS_ORDERED_RECEIVED_DIFFER):
660                                    break
661
662                    # all rows should be refreshed now, but batch status still needs it
663                    self.refresh_batch_status(batch.truck_dump_batch)
664                    self.refresh_batch_status(batch)
665
666        return result
667
668    def refresh_batch_status(self, batch):
669        rows = batch.active_rows()
670
671        # "unknown product" is the most egregious status; we'll "prefer" it
672        # over all others in order to bring it to user's attention
673        if any([row.status_code == row.STATUS_PRODUCT_NOT_FOUND for row in rows]):
674            batch.status_code = batch.STATUS_UNKNOWN_PRODUCT
675
676        # for now anything else is considered ok
677        else:
678            batch.status_code = batch.STATUS_OK
679
680        # truck dump parent batch gets status to reflect how much is (un)claimed
681        if batch.is_truck_dump_parent():
682
683            # batch is "claimed" only if all rows are "settled" so to speak
684            if all([row.truck_dump_status == row.STATUS_TRUCKDUMP_CLAIMED
685                    for row in rows]):
686                batch.truck_dump_status = batch.STATUS_TRUCKDUMP_CLAIMED
687
688            # otherwise just call it "unclaimed"
689            else:
690                batch.truck_dump_status = batch.STATUS_TRUCKDUMP_UNCLAIMED
691
692    def locate_product_for_entry(self, session, entry, lookup_by_code=True):
693        """
694        Try to locate the product represented by the given "entry" - which is
695        assumed to be a "raw" string, e.g. as obtained from scanner or other
696        user input, or from a vendor-supplied spreadsheet etc.  (In other words
697        this method is not told "what" sort of entry it is being given.)
698
699        :param lookup_by_code: If set to ``False``, then the method will
700           attempt a lookup *only* on the product key field (either ``upc`` or
701           ``item_id`` depending on config).  If set to ``True`` (the default)
702           then the method will also attempt a lookup in the ``ProductCode``
703           table, aka. alternate codes.
704        """
705        # try to locate product by uuid before other, more specific key
706        product = session.query(model.Product).get(entry)
707        if product:
708            return product
709
710        product_key = self.config.product_key()
711        if product_key == 'upc':
712
713            if entry.isdigit():
714
715                # we first assume the user entry *does* include check digit
716                provided = GPC(entry, calc_check_digit=False)
717                product = api.get_product_by_upc(session, provided)
718                if product:
719                    return product
720
721                # but we can also calculate a check digit and try that
722                checked = GPC(entry, calc_check_digit='upc')
723                product = api.get_product_by_upc(session, checked)
724                if product:
725                    return product
726
727        elif product_key == 'item_id':
728
729            # try to locate product by item_id
730            product = api.get_product_by_item_id(session, entry)
731            if product:
732                return product
733
734        # if we made it this far, lookup by product key failed.
735
736        # okay then, let's maybe attempt lookup by "alternate" code
737        if lookup_by_code:
738            product = api.get_product_by_code(session, entry)
739            if product:
740                return product
741
742    def locate_product(self, row, session=None, vendor=None):
743        """
744        Try to locate the product represented by the given row.  Default
745        behavior here, is to do a simple lookup on either ``Product.upc`` or
746        ``Product.item_id``, depending on which is configured as your product
747        key field.
748        """
749        if not session:
750            session = orm.object_session(row)
751        product_key = self.config.product_key()
752
753        if product_key == 'upc':
754            if row.upc:
755                product = api.get_product_by_upc(session, row.upc)
756                if product:
757                    return product
758
759        elif product_key == 'item_id':
760            if row.item_id:
761                product = api.get_product_by_item_id(session, row.item_id)
762                if product:
763                    return product
764
765        # product key didn't work, but vendor item code just might
766        if row.vendor_code:
767            product = api.get_product_by_vendor_code(session, row.vendor_code,
768                                                     vendor=vendor or row.batch.vendor)
769            if product:
770                return product
771
772        # before giving up, let's do a lookup on alt codes too
773        if row.item_entry:
774            product = api.get_product_by_code(session, row.item_entry)
775            if product:
776                return product
777
778    def transform_pack_to_unit(self, row):
779        """
780        Transform the given row, which is assumed to associate with a "pack"
781        item, such that it associates with the "unit" item instead.
782        """
783        if not row.product:
784            return
785        if not row.product.is_pack_item():
786            return
787
788        assert row.batch.is_truck_dump_parent()
789
790        # remove any existing claims for this (parent) row
791        if row.claims:
792            session = orm.object_session(row)
793            del row.claims[:]
794            # set temporary status for the row, if needed.  this is to help
795            # with claiming logic below
796            if row.status_code in (row.STATUS_TRUCKDUMP_PARTCLAIMED,
797                                   row.STATUS_TRUCKDUMP_CLAIMED,
798                                   row.STATUS_TRUCKDUMP_OVERCLAIMED):
799                row.status_code = row.STATUS_TRUCKDUMP_UNCLAIMED
800            session.flush()
801            session.refresh(row)
802
803        # pretty sure this is the only status we're expecting at this point...
804        assert row.status_code == row.STATUS_TRUCKDUMP_UNCLAIMED
805
806        # replace the row's product association
807        pack = row.product
808        unit = pack.unit
809        row.product = unit
810        row.item_id = unit.item_id
811        row.upc = unit.upc
812
813        # set new case quantity, per preferred cost
814        cost = unit.cost_for_vendor(row.batch.vendor)
815        row.case_quantity = (cost.case_size or 1) if cost else 1
816
817        # must recalculate "units received" since those were for the pack item
818        if row.units_received:
819            row.units_received *= pack.pack_size
820
821        # try to establish "claims" between parent and child(ren)
822        self.make_truck_dump_claims_for_parent_row(row)
823
824        # refresh the row itself, so product attributes will be updated
825        self.refresh_row(row)
826
827        # refresh status for the batch(es) proper, just in case this changed things
828        self.refresh_batch_status(row.batch)
829        for child in row.batch.truck_dump_children:
830            self.refresh_batch_status(child)
831
832    def make_truck_dump_claims_for_parent_row(self, row):
833        """
834        Try to establish all "truck dump claims" between parent and children,
835        for the given parent row.
836        """
837        for child in row.batch.truck_dump_children:
838            child_rows = [child_row for child_row in child.active_rows()
839                          if child_row.product_uuid == row.product.uuid]
840            if child_rows:
841                self.make_truck_dump_claims(row, child_rows)
842                if row.status_code not in (row.STATUS_TRUCKDUMP_UNCLAIMED,
843                                           row.STATUS_TRUCKDUMP_PARTCLAIMED):
844                    break
845
846    def refresh_row(self, row, initial=False):
847        """
848        Refreshing a row will A) assume that ``row.product`` is already set to
849        a valid product, or else will attempt to locate the product, and B)
850        update various other fields on the row (description, size, etc.)  to
851        reflect the current product data.  It also will adjust the batch PO
852        total per the row PO total.
853        """
854        batch = row.batch
855
856        # first identify the product, or else we have nothing more to do
857        product = row.product
858        if not product:
859            product = self.locate_product(row)
860            if product:
861                row.product = product
862            else:
863                row.status_code = row.STATUS_PRODUCT_NOT_FOUND
864                return
865
866        # update various (cached) product attributes for the row
867        cost = product.cost_for_vendor(batch.vendor)
868        row.upc = product.upc
869        row.item_id = product.item_id
870        row.brand_name = six.text_type(product.brand or '')
871        row.description = product.description
872        row.size = product.size
873        if product.department:
874            row.department_number = product.department.number
875            row.department_name = product.department.name
876        else:
877            row.department_number = None
878            row.department_name = None
879        row.vendor_code = cost.code if cost else None
880
881        # figure out the effective case quantity, and whether it differs with
882        # what we previously had on file
883        case_quantity_differs = False
884        if cost and cost.case_size:
885            if not row.case_quantity:
886                row.case_quantity = cost.case_size
887            elif row.case_quantity != cost.case_size:
888                if batch.is_truck_dump_parent():
889                    if batch.truck_dump_children_first:
890                        # supposedly our case quantity came from a truck dump
891                        # child row, which we assume to be authoritative
892                        case_quantity_differs = True
893                    else:
894                        # truck dump has no children yet, which means we have
895                        # no special authority for case quantity; therefore
896                        # should treat master cost record as authority
897                        row.case_quantity = cost.case_size
898                else:
899                    case_quantity_differs = True
900
901        # determine PO / invoice unit cost if necessary
902        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING and row.po_unit_cost is None:
903            row.po_unit_cost = self.get_unit_cost(row.product, batch.vendor)
904        if batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING and row.invoice_unit_cost is None:
905            row.invoice_unit_cost = row.po_unit_cost or (cost.unit_cost if cost else None)
906
907        # update PO / invoice totals for row and batch
908        self.refresh_totals(row, cost, initial)
909
910        # all that's left should be setting status for the row...and that logic
911        # will primarily depend on the 'mode' for this purchase batch
912
913        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
914            row.status_code = row.STATUS_OK
915
916        elif batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
917
918            # first check to see if we have *any* confirmed items
919            if not (row.cases_received or row.units_received or
920                    row.cases_damaged or row.units_damaged or
921                    row.cases_expired or row.units_expired or
922                    row.cases_mispick or row.units_mispick):
923
924                # no, we do not have any confirmed items...
925
926                # TODO: is this right? should row which ordered nothing just be removed?
927                if batch.order_quantities_known and not (row.cases_ordered or row.units_ordered):
928                    row.status_code = row.STATUS_OK
929                # TODO: is this right? should out of stock just be a filter for
930                # the user to specify, or should it affect status?
931                elif row.out_of_stock:
932                    row.status_code = row.STATUS_OUT_OF_STOCK
933                else:
934                    row.status_code = row.STATUS_INCOMPLETE
935
936                # truck dump parent rows are also given status for that, which
937                # reflects claimed vs. pending, i.e. child reconciliation
938                if batch.is_truck_dump_parent():
939                    row.truck_dump_status = row.STATUS_TRUCKDUMP_CLAIMED
940
941            else: # we do have some confirmed items
942
943                # primary status code for row should ideally reflect ordered
944                # vs. received, although there are some exceptions
945                if case_quantity_differs:
946                    row.status_code = row.STATUS_CASE_QUANTITY_DIFFERS
947                    row.status_text = "batch has {} but master cost has {}".format(
948                        repr(row.case_quantity), repr(cost.case_size))
949                elif batch.order_quantities_known and (
950                        self.get_units_ordered(row) != self.get_units_accounted_for(row)):
951                    row.status_code = row.STATUS_ORDERED_RECEIVED_DIFFER
952                # TODO: is this right? should out of stock just be a filter for
953                # the user to specify, or should it affect status?
954                elif row.out_of_stock:
955                    row.status_code = row.STATUS_OUT_OF_STOCK
956                else:
957                    row.status_code = row.STATUS_OK
958
959                # truck dump parent rows are also given status for that, which
960                # reflects claimed vs. pending, i.e. child reconciliation
961                if batch.is_truck_dump_parent():
962                    confirmed = self.get_units_confirmed(row)
963                    claimed = self.get_units_claimed(row)
964                    if claimed == confirmed:
965                        row.truck_dump_status = row.STATUS_TRUCKDUMP_CLAIMED
966                    elif not claimed:
967                        row.truck_dump_status = row.STATUS_TRUCKDUMP_UNCLAIMED
968                    elif claimed < confirmed:
969                        row.truck_dump_status = row.STATUS_TRUCKDUMP_PARTCLAIMED
970                    elif claimed > confirmed:
971                        row.truck_dump_status = row.STATUS_TRUCKDUMP_OVERCLAIMED
972                    else:
973                        raise NotImplementedError
974
975        else:
976            raise NotImplementedError("can't refresh row for batch of mode: {}".format(
977                self.enum.PURCHASE_BATCH_MODE.get(batch.mode, "unknown ({})".format(batch.mode))))
978
979    def receive_row(self, row, mode='received', cases=None, units=None, **kwargs):
980        """
981        This method is arguably the workhorse of the whole process. Callers
982        should invoke it as they receive input from the user during the
983        receiving workflow.
984
985        Each call to this method must include the row to be updated, as well as
986        the details of the update.  These details should reflect "changes"
987        which are to be made, as opposed to "final values" for the row.  In
988        other words if a row already has ``cases_received == 1`` and the user
989        is receiving a second case, this method should be called like so::
990
991           handler.receive_row(row, mode='received', cases=1)
992
993        The row will be updated such that ``cases_received == 2``; the main
994        point here is that the caller should *not* specify ``cases=2`` because
995        it is the handler's job to "apply changes" from the caller.  (If the
996        caller speficies ``cases=2`` then the row would end up with
997        ``cases_received == 3``.)
998
999        For "undo" type adjustments, caller can just send a negative amount,
1000        and the handler will apply the changes as expected::
1001
1002           handler.receive_row(row, mode='received', cases=-1)
1003
1004        Note that each call must specify *either* a (non-empty) ``cases`` or
1005        ``units`` value, but *not* both!
1006
1007        :param rattail.db.model.batch.purchase.PurchaseBatchRow row: Batch row
1008           which is to be updated with the given receiving data.  The row must
1009           exist, i.e. this method will not create a new row for you.
1010
1011        :param str mode: Must be one of the receiving modes which are
1012           "supported" according to the handler.  Possible modes include:
1013
1014           * ``'received'``
1015           * ``'damaged'``
1016           * ``'expired'``
1017           * ``'mispick'``
1018
1019        :param decimal.Decimal cases: Case quantity for the update, if applicable.
1020
1021        :param decimal.Decimal units: Unit quantity for the update, if applicable.
1022
1023        :param datetime.date expiration_date: Expiration date for the update,
1024           if applicable.  Only used if ``mode='expired'``.
1025
1026        This method exists mostly to consolidate the various logical steps which
1027        must be taken for each new receiving input from the user.  Under the hood
1028        it delegates to a few other methods:
1029
1030        * :meth:`receiving_update_row_attrs()`
1031        * :meth:`receiving_update_row_credits()`
1032        * :meth:`receiving_update_row_children()`
1033        """
1034        # make sure we have cases *or* units
1035        if not (cases or units):
1036            raise ValueError("must provide amount for cases *or* units")
1037        if cases and units:
1038            raise ValueError("must provide amount for cases *or* units (but not both)")
1039
1040        # make sure we have a receiving batch
1041        if row.batch.mode != self.enum.PURCHASE_BATCH_MODE_RECEIVING:
1042            raise NotImplementedError("receive_row() is only for receiving batches")
1043
1044        # update the given row
1045        self.receiving_update_row_attrs(row, mode, cases, units)
1046
1047        # update the given row's credits
1048        self.receiving_update_row_credits(row, mode, cases, units, **kwargs)
1049
1050        # update the given row's "children" (if this is truck dump parent)
1051        self.receiving_update_row_children(row, mode, cases, units, **kwargs)
1052
1053    def receiving_update_row_attrs(self, row, mode, cases, units):
1054        """
1055        Apply a receiving update to the row's attributes.
1056
1057        Note that this should not be called directly; it is invoked as part of
1058        :meth:`receive_row()`.
1059        """
1060        batch = row.batch
1061
1062        # add values as-is to existing case/unit amounts.  note
1063        # that this can sometimes give us negative values!  e.g. if
1064        # user scans 1 CS and then subtracts 2 EA, then we would
1065        # have 1 / -2 for our counts.  but we consider that to be
1066        # expected, and other logic must allow for the possibility
1067        if cases:
1068            setattr(row, 'cases_{}'.format(mode),
1069                    (getattr(row, 'cases_{}'.format(mode)) or 0) + cases)
1070        if units:
1071            setattr(row, 'units_{}'.format(mode),
1072                    (getattr(row, 'units_{}'.format(mode)) or 0) + units)
1073
1074        # undo any totals previously in effect for the row, then refresh.  this
1075        # updates some totals as well as status for the row
1076        if row.invoice_total:
1077            batch.invoice_total -= row.invoice_total
1078        self.refresh_row(row)
1079
1080    def receiving_update_row_credits(self, row, mode, cases, units, **kwargs):
1081        """
1082        Apply a receiving update to the row's credits, if applicable.
1083
1084        Note that this should not be called directly; it is invoked as part of
1085        :meth:`receive_row()`.
1086        """
1087        batch = row.batch
1088
1089        # only certain modes should involve credits
1090        if mode not in ('damaged', 'expired', 'mispick'):
1091            return
1092
1093        # TODO: need to add mispick support obviously
1094        if mode == 'mispick':
1095            raise NotImplementedError("mispick credits not yet supported")
1096
1097        # TODO: must account for negative values here! i.e. remove credit in
1098        # some scenarios, perhaps using `kwargs` to find the match?
1099        if (cases and cases > 0) or (units and units > 0):
1100            positive = True
1101        else:
1102            positive = False
1103            raise NotImplementedError("TODO: add support for negative values when updating credits")
1104
1105        # always make new credit; never aggregate
1106        credit = model.PurchaseBatchCredit()
1107        credit.credit_type = mode
1108        credit.store = batch.store
1109        credit.vendor = batch.vendor
1110        credit.date_ordered = batch.date_ordered
1111        credit.date_shipped = batch.date_shipped
1112        credit.date_received = batch.date_received
1113        credit.invoice_number = batch.invoice_number
1114        credit.invoice_date = batch.invoice_date
1115        credit.product = row.product
1116        credit.upc = row.upc
1117        credit.vendor_item_code = row.vendor_code
1118        credit.brand_name = row.brand_name
1119        credit.description = row.description
1120        credit.size = row.size
1121        credit.department_number = row.department_number
1122        credit.department_name = row.department_name
1123        credit.case_quantity = row.case_quantity
1124        credit.cases_shorted = cases
1125        credit.units_shorted = units
1126        credit.invoice_line_number = row.invoice_line_number
1127        credit.invoice_case_cost = row.invoice_case_cost
1128        credit.invoice_unit_cost = row.invoice_unit_cost
1129        credit.invoice_total = row.invoice_total
1130
1131        # calculate credit total
1132        # TODO: should this leverage case cost if present?
1133        credit_units = self.get_units(credit.cases_shorted,
1134                                      credit.units_shorted,
1135                                      credit.case_quantity)
1136        credit.credit_total = credit_units * (credit.invoice_unit_cost or 0)
1137
1138        # apply other attributes to credit, per caller kwargs
1139        credit.product_discarded = kwargs.get('discarded')
1140        if mode == 'expired':
1141            credit.expiration_date = kwargs.get('expiration_date')
1142        elif mode == 'mispick' and kwargs.get('mispick_product'):
1143            mispick_product = kwargs['mispick_product']
1144            credit.mispick_product = mispick_product
1145            credit.mispick_upc = mispick_product.upc
1146            if mispick_product.brand:
1147                credit.mispick_brand_name = mispick_product.brand.name
1148            credit.mispick_description = mispick_product.description
1149            credit.mispick_size = mispick_product.size
1150
1151        # attach credit to row
1152        row.credits.append(credit)
1153
1154    def receiving_update_row_children(self, row, mode, cases, units, **kwargs):
1155        """
1156        Apply a receiving update to the row's "children", if applicable.
1157
1158        Note that this should not be called directly; it is invoked as part of
1159        :meth:`receive_row()`.
1160
1161        This logic only applies to a "truck dump parent" row, since that is the
1162        only type which can have "children".  Also this logic is assumed only
1163        to apply if using the "children first" workflow.  If these criteria are
1164        not met then nothing is done.
1165
1166        This method is ultimately responsible for updating "everything"
1167        (relevant) about the children of the given parent row.  This includes
1168        updating the child row(s) as well as the "claim" records used for
1169        reconciliation, as well as any child credit(s).  However most of the
1170        heavy lifting is done by :meth:`receiving_update_row_child()`.
1171        """
1172        batch = row.batch
1173
1174        # updating row children is only applicable for truck dump parent, and
1175        # even then only if "children first" workflow
1176        if not batch.is_truck_dump_parent():
1177            return
1178        # TODO: maybe should just check for `batch.truck_dump_children` instead?
1179        if not batch.truck_dump_children_first:
1180            return
1181
1182        # apply changes to child row(s) until we exhaust update quantities
1183        while cases or units:
1184
1185            # find the "best match" child per current quantities, or quit if we
1186            # can no longer find any child match at all
1187            child_row = self.receiving_find_best_child_row(row, mode, cases, units)
1188            if not child_row:
1189                break
1190
1191            # apply update to child, which should reduce our quantities
1192            before = cases, units
1193            cases, units = self.receiving_update_row_child(row, child_row, mode, cases, units, **kwargs)
1194            if (cases, units) == before:
1195                raise RuntimeError("infinite loop detected; aborting")
1196
1197        # undo any totals previously in effect for the row, then refresh.  this
1198        # updates some totals as well as status for the row
1199        if row.invoice_total:
1200            batch.invoice_total -= row.invoice_total
1201        self.refresh_row(row)
1202
1203    def receiving_update_row_child(self, parent_row, child_row, mode, cases, units, **kwargs):
1204        """
1205        Update the given child row attributes, as well as the "claim" record
1206        which ties it to the parent, as well as any credit(s) which may apply.
1207
1208        Ideally the child row can accommodate the "full" case/unit amounts
1209        given, but if not then it must do as much as it can.  Note that the
1210        child row should have been located via :meth:`receiving_find_best_child_row()`
1211        and therefore should be able to accommodate *something* at least.
1212
1213        This method returns a 2-tuple of ``(cases, units)`` which reflect the
1214        amounts it was *not* able to claim (or relinquish, if incoming amounts
1215        are negative).  In other words these are the "leftovers" which still
1216        need to be dealt with somehow.
1217        """
1218        # were we given positive or negative values for the update?
1219        if (cases and cases > 0) or (units and units > 0):
1220            positive = True
1221        else:
1222            positive = False
1223
1224        ##############################
1225
1226        def update(cases, units):
1227
1228            # update child claim
1229            claim = get_claim()
1230            if cases:
1231                setattr(claim, 'cases_{}'.format(mode),
1232                        (getattr(claim, 'cases_{}'.format(mode)) or 0) + cases)
1233            if units:
1234                setattr(claim, 'units_{}'.format(mode),
1235                        (getattr(claim, 'units_{}'.format(mode)) or 0) + units)
1236            # remove claim if now empty (should only happen if negative values?)
1237            if claim.is_empty():
1238                parent_row.claims.remove(claim)
1239
1240            # update child row
1241            self.receiving_update_row_attrs(child_row, mode, cases, units)
1242            if cases:
1243                child_row.cases_ordered_claimed += cases
1244                child_row.cases_ordered_pending -= cases
1245            if units:
1246                child_row.units_ordered_claimed += units
1247                child_row.units_ordered_pending -= units
1248
1249            # update child credit, if applicable
1250            self.receiving_update_row_credits(child_row, mode, cases, units, **kwargs)
1251
1252        def get_claim():
1253            claims = [claim for claim in parent_row.claims
1254                      if claim.claiming_row is child_row]
1255            if claims:
1256                if len(claims) > 1:
1257                    raise ValueError("child row has too many claims on parent!")
1258                return claims[0]
1259            claim = model.PurchaseBatchRowClaim()
1260            claim.claiming_row = child_row
1261            parent_row.claims.append(claim)
1262            return claim
1263
1264        ##############################
1265
1266        # first we try to accommodate the full "as-is" amounts, if possible
1267        if positive:
1268            if cases and units:
1269                if child_row.cases_ordered_pending >= cases and child_row.units_ordered_pending >= units:
1270                    update(cases, units)
1271                    return 0, 0
1272            elif cases:
1273                if child_row.cases_ordered_pending >= cases:
1274                    update(cases, 0)
1275                    return 0, 0
1276            else: # units
1277                if child_row.units_ordered_pending >= units:
1278                    update(0, units)
1279                    return 0, 0
1280        else: # negative
1281            if cases and units:
1282                if child_row.cases_ordered_claimed >= -cases and child_row.units_ordered_claimed >= -units:
1283                    update(cases, units)
1284                    return 0, 0
1285            elif cases:
1286                if child_row.cases_ordered_claimed >= -cases:
1287                    update(cases, 0)
1288                    return 0, 0
1289            else: # units
1290                if child_row.units_ordered_claimed >= -units:
1291                    update(0, units)
1292                    return 0, 0
1293
1294        # next we try a couple more variations on that theme, aiming for "as
1295        # much as possible, as simply as possible"
1296        if cases and units:
1297            if positive:
1298                if child_row.cases_ordered_pending >= cases:
1299                    update(cases, 0)
1300                    return 0, units
1301                if child_row.units_ordered_pending >= units:
1302                    update(0, units)
1303                    return cases, 0
1304            else: # negative
1305                if child_row.cases_ordered_claimed >= -cases:
1306                    update(cases, 0)
1307                    return 0, units
1308                if child_row.units_ordered_claimed >= -units:
1309                    update(0, units)
1310                    return cases, 0
1311
1312        # okay then, try to (simply) use up any "child" quantities
1313        if positive:
1314            if cases and units and (child_row.cases_ordered_pending
1315                                    and child_row.units_ordered_pending):
1316                update(child_row.cases_ordered_pending, child_row.units_ordered_pending)
1317                return (cases - child_row.cases_ordered_pending,
1318                        units - child_row.units_ordered_pending)
1319            if cases and child_row.cases_ordered_pending:
1320                update(child_row.cases_ordered_pending, 0)
1321                return cases - child_row.cases_ordered_pending, 0
1322            if units and child_row.units_ordered_pending:
1323                update(0, child_row.units_ordered_pending)
1324                return 0, units - child_row.units_ordered_pending
1325        else: # negative
1326            if cases and units and (child_row.cases_ordered_claimed
1327                                    and child_row.units_ordered_claimed):
1328                update(-child_row.cases_ordered_claimed, -child_row.units_ordered_claimed)
1329                return (cases + child_row.cases_ordered_claimed,
1330                        units + child_row.units_ordered_claimed)
1331            if cases and child_row.cases_ordered_claimed:
1332                update(-child_row.cases_ordered_claimed, 0)
1333                return cases + child_row.cases_ordered_claimed, 0
1334            if units and child_row.units_ordered_claimed:
1335                update(0, -child_row.units_ordered_claimed)
1336                return 0, units + child_row.units_ordered_claimed
1337
1338        # looks like we're gonna have to split some cases, one way or another
1339        if parent_row.case_quantity != child_row.case_quantity:
1340            raise NotImplementedError("cannot split case when parent/child disagree about size")
1341        if positive:
1342            if cases and child_row.units_ordered_pending:
1343                if child_row.units_ordered_pending >= parent_row.case_quantity:
1344                    unit_cases = child_row.units_ordered_pending // parent_row.case_quantity
1345                    if unit_cases >= cases:
1346                        update(0, cases * parent_row.case_quantity)
1347                        return 0, units
1348                    else: # unit_cases < cases
1349                        update(0, unit_cases * parent_row.case_quantity)
1350                        return cases - unit_cases, units
1351                else: # units_pending < case_size
1352                    update(0, child_row.units_ordered_pending)
1353                    return (cases - 1,
1354                            (units or 0) + parent_row.case_quantity - child_row.units_ordered_pending)
1355            if units and child_row.cases_ordered_pending:
1356                if units >= parent_row.case_quantity:
1357                    unit_cases = units // parent_row.case_quantity
1358                    if unit_cases <= child_row.cases_ordered_pending:
1359                        update(unit_cases, 0)
1360                        return 0, units - (unit_cases * parent_row.case_quantity)
1361                    else: # unit_cases > cases_pending
1362                        update(child_row.cases_ordered_pending, 0)
1363                        return 0, units - (child_row.cases_ordered_pending * parent_row.case_quantity)
1364                else: # units < case_size
1365                    update(0, units)
1366                    return 0, 0
1367        else: # negative
1368            if cases and child_row.units_ordered_claimed:
1369                if child_row.units_ordered_claimed >= parent_row.case_quantity:
1370                    unit_cases = child_row.units_ordered_claimed // parent_row.case_quantity
1371                    if unit_cases >= -cases:
1372                        update(0, cases * parent_row.case_quantity)
1373                        return 0, units
1374                    else: # unit_cases < -cases
1375                        update(0, -unit_cases * parent_row.case_quantity)
1376                        return cases + unit_cases, units
1377                else: # units_claimed < case_size
1378                    update(0, -child_row.units_ordered_claimed)
1379                    return (cases + 1,
1380                            (units or 0) - parent_row.case_quantity + child_row.units_ordered_claimed)
1381            if units and child_row.cases_ordered_claimed:
1382                if -units >= parent_row.case_quantity:
1383                    unit_cases = -units // parent_row.case_quantity
1384                    if unit_cases <= child_row.cases_ordered_claimed:
1385                        update(-unit_cases, 0)
1386                        return 0, units + (unit_cases * parent_row.case_quantity)
1387                    else: # unit_cases > cases_claimed
1388                        update(-child_row.cases_ordered_claimed, 0)
1389                        return 0, units + (child_row.cases_ordered_claimed * parent_row.case_quantity)
1390                else: # -units < case_size
1391                    update(0, units)
1392                    return 0, 0
1393
1394        # TODO: this should theoretically never happen; should log/raise error?
1395        log.warning("unable to claim/relinquish any case/unit amounts for child row: %s", child_row)
1396        return cases, units
1397
1398    def receiving_find_best_child_row(self, row, mode, cases, units):
1399        """
1400        Locate and return the "best match" child row, for the given parent row
1401        and receiving update details.  The idea here is that the parent row
1402        will represent the "receiving" side of things, whereas the child row
1403        will be the "ordering" side.
1404
1405        For instance if the update is for say, "received 2 CS" and there are
1406        two child rows, one of which is for 1 CS and the other 2 CS, the latter
1407        will be returned.  This logic is capable of "splitting" a case where
1408        necessary, in order to find a partial match etc.
1409        """
1410        parent_row = row
1411        parent_batch = parent_row.batch
1412
1413        if not parent_row.product:
1414            raise NotImplementedError("not sure how to find best match for unknown product")
1415
1416        if not (cases or units):
1417            raise ValueError("must provide amount for cases and/or units")
1418
1419        if cases and units and (
1420                (cases > 0 and units < 0) or (cases < 0 and units > 0)):
1421            raise NotImplementedError("not sure how to handle mixed pos/neg for case/unit amounts")
1422
1423        # were we given positive or negative values for the update?
1424        if (cases and cases > 0) or (units and units > 0):
1425            positive = True
1426        else:
1427            positive = False
1428
1429        # first we collect all potential child rows
1430        all_child_rows = []
1431        for child_batch in parent_batch.truck_dump_children:
1432            child_rows = [child_row for child_row in child_batch.active_rows()
1433                          if child_row.product_uuid == parent_row.product.uuid]
1434            for child_row in child_rows:
1435
1436                # for each child row we also calculate "claimed" vs. "pending" amounts
1437
1438                # cases_ordered
1439                child_row.cases_ordered_claimed = sum([(claim.cases_received or 0)
1440                                                       + (claim.cases_damaged or 0)
1441                                                       + (claim.cases_expired or 0)
1442                                                       for claim in child_row.truck_dump_claims])
1443                child_row.cases_ordered_pending = (child_row.cases_ordered or 0) - child_row.cases_ordered_claimed
1444
1445                # units_ordered
1446                child_row.units_ordered_claimed = sum([(claim.units_received or 0)
1447                                                       + (claim.units_damaged or 0)
1448                                                       + (claim.units_expired or 0)
1449                                                       for claim in child_row.truck_dump_claims])
1450                child_row.units_ordered_pending = (child_row.units_ordered or 0) - child_row.units_ordered_claimed
1451
1452                # maybe account for split cases
1453                if child_row.units_ordered_pending < 0:
1454                    split_cases = -child_row.units_ordered_pending // child_row.case_quantity + 1
1455                    if split_cases > child_row.cases_ordered_pending:
1456                        raise ValueError("too many cases have been split?")
1457                    child_row.cases_ordered_pending -= split_cases
1458                    child_row.units_ordered_pending += split_cases * child_row.case_quantity
1459
1460                all_child_rows.append(child_row)
1461
1462        def sortkey(row):
1463            if positive:
1464                return self.get_units(row.cases_ordered_pending,
1465                                      row.units_ordered_pending,
1466                                      row.case_quantity)
1467            else: # negative
1468                return self.get_units(row.cases_ordered_claimed,
1469                                      row.units_ordered_claimed,
1470                                      row.case_quantity)
1471
1472        # sort child rows such that smallest (relevant) quantities come first;
1473        # idea being we would prefer the "least common denominator" to match
1474        all_child_rows.sort(key=sortkey)
1475
1476        # first try to find an exact match
1477        for child_row in all_child_rows:
1478            if cases and units:
1479                if positive:
1480                    if child_row.cases_ordered_pending == cases and child_row.units_ordered_pending == units:
1481                        return child_row
1482                else: # negative
1483                    if child_row.cases_ordered_claimed == cases and child_row.units_ordered_claimed == units:
1484                        return child_row
1485            elif cases:
1486                if positive:
1487                    if child_row.cases_ordered_pending == cases:
1488                        return child_row
1489                else: # negative
1490                    if child_row.cases_ordered_claimed == cases:
1491                        return child_row
1492            else: # units
1493                if positive:
1494                    if child_row.units_ordered_pending == units:
1495                        return child_row
1496                else: # negative
1497                    if child_row.units_ordered_claimed == units:
1498                        return child_row
1499
1500        # next we try to find the "first" (smallest) match which satisfies, but
1501        # which does so *without* having to split up any cases
1502        for child_row in all_child_rows:
1503            if cases and units:
1504                if positive:
1505                    if child_row.cases_ordered_pending >= cases and child_row.units_ordered_pending >= units:
1506                        return child_row
1507                else: # negative
1508                    if child_row.cases_ordered_claimed >= -cases and child_row.units_ordered_claimed >= -units:
1509                        return child_row
1510            elif cases:
1511                if positive:
1512                    if child_row.cases_ordered_pending >= cases:
1513                        return child_row
1514                else: # negative
1515                    if child_row.cases_ordered_claimed >= -cases:
1516                        return child_row
1517            else: # units
1518                if positive:
1519                    if child_row.units_ordered_pending >= units:
1520                        return child_row
1521                else: # negative
1522                    if child_row.units_ordered_claimed >= -units:
1523                        return child_row
1524
1525        # okay, we're getting desperate now; let's start splitting cases and
1526        # may the first possible match (which fully satisfies) win...
1527        incoming_units = self.get_units(cases, units, parent_row.case_quantity)
1528        for child_row in all_child_rows:
1529            if positive:
1530                pending_units = self.get_units(child_row.cases_ordered_pending,
1531                                               child_row.units_ordered_pending,
1532                                               child_row.case_quantity)
1533                if pending_units >= incoming_units:
1534                    return child_row
1535            else: # negative
1536                claimed_units = self.get_units(child_row.cases_ordered_claimed,
1537                                               child_row.units_ordered_claimed,
1538                                               child_row.case_quantity)
1539                if claimed_units >= -incoming_units:
1540                    return child_row
1541
1542        # and now we're even more desperate.  at this point no child row can
1543        # fully (by itself) accommodate the update at hand, which means we must
1544        # look for the first child which can accommodate anything at all, and
1545        # settle for the partial match.  note that we traverse the child row
1546        # list *backwards* here, hoping for the "biggest" match
1547        for child_row in reversed(all_child_rows):
1548            if positive:
1549                if child_row.cases_ordered_pending or child_row.units_ordered_pending:
1550                    return child_row
1551            else: # negative
1552                if child_row.cases_ordered_claimed or child_row.units_ordered_claimed:
1553                    return child_row
1554
1555    def remove_row(self, row):
1556        """
1557        When removing a row from purchase batch, (maybe) must also update some
1558        totals for the batch.
1559        """
1560        batch = row.batch
1561
1562        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
1563            if row.po_total:
1564                batch.po_total -= row.po_total
1565
1566        if batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
1567            if row.invoice_total:
1568                batch.invoice_total -= row.invoice_total
1569
1570        super(PurchaseBatchHandler, self).remove_row(row)
1571
1572    def refresh_totals(self, row, cost, initial):
1573        batch = row.batch
1574
1575        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
1576            if row.po_unit_cost:
1577                row.po_total = row.po_unit_cost * self.get_units_ordered(row)
1578                batch.po_total = (batch.po_total or 0) + row.po_total
1579            else:
1580                row.po_total = None
1581
1582        elif batch.mode in (self.enum.PURCHASE_BATCH_MODE_RECEIVING,
1583                            self.enum.PURCHASE_BATCH_MODE_COSTING):
1584            if row.invoice_unit_cost:
1585                row.invoice_total = row.invoice_unit_cost * self.get_units_accounted_for(row)
1586                batch.invoice_total = (batch.invoice_total or 0) + row.invoice_total
1587            else:
1588                row.invoice_total = None
1589
1590    def get_unit_cost(self, product, vendor):
1591        """
1592        Must return the PO unit cost for the given product, from the given vendor.
1593        """
1594        cost = product.cost_for_vendor(vendor) or product.cost
1595        if cost:
1596            return cost.unit_cost
1597
1598    def get_units(self, cases, units, case_quantity):
1599        case_quantity = case_quantity or 1
1600        return (units or 0) + case_quantity * (cases or 0)
1601
1602    def get_units_ordered(self, row, case_quantity=None):
1603        case_quantity = case_quantity or row.case_quantity or 1
1604        return self.get_units(row.cases_ordered, row.units_ordered, case_quantity)
1605
1606    # TODO: we now have shipped quantities...should return sum of those instead?
1607    def get_units_shipped(self, row, case_quantity=None):
1608        case_quantity = case_quantity or row.case_quantity or 1
1609        units_damaged = (row.units_damaged or 0) + case_quantity * (row.cases_damaged or 0)
1610        units_expired = (row.units_expired or 0) + case_quantity * (row.cases_expired or 0)
1611        return self.get_units_received(row) + units_damaged + units_expired
1612
1613    def get_units_received(self, row, case_quantity=None):
1614        case_quantity = case_quantity or row.case_quantity or 1
1615        return self.get_units(row.cases_received, row.units_received, case_quantity)
1616
1617    def get_units_damaged(self, row, case_quantity=None):
1618        case_quantity = case_quantity or row.case_quantity or 1
1619        return self.get_units(row.cases_damaged, row.units_damaged, case_quantity)
1620
1621    def get_units_expired(self, row, case_quantity=None):
1622        case_quantity = case_quantity or row.case_quantity or 1
1623        return self.get_units(row.cases_expired, row.units_expired, case_quantity)
1624
1625    def get_units_confirmed(self, row, case_quantity=None):
1626        received = self.get_units_received(row, case_quantity=case_quantity)
1627        damaged = self.get_units_damaged(row, case_quantity=case_quantity)
1628        expired = self.get_units_expired(row, case_quantity=case_quantity)
1629        return received + damaged + expired
1630
1631    def get_units_mispick(self, row, case_quantity=None):
1632        case_quantity = case_quantity or row.case_quantity or 1
1633        return self.get_units(row.cases_mispick, row.units_mispick, case_quantity)
1634
1635    def get_units_accounted_for(self, row, case_quantity=None):
1636        confirmed = self.get_units_confirmed(row, case_quantity=case_quantity)
1637        mispick = self.get_units_mispick(row, case_quantity=case_quantity)
1638        return confirmed + mispick
1639
1640    def get_units_shorted(self, obj, case_quantity=None):
1641        case_quantity = case_quantity or obj.case_quantity or 1
1642        if hasattr(obj, 'cases_shorted'):
1643            # obj is really a credit
1644            return self.get_units(obj.cases_shorted, obj.units_shorted, case_quantity)
1645        else:
1646            # obj is a row, so sum the credits
1647            return sum([self.get_units(credit.cases_shorted, credit.units_shorted, case_quantity)
1648                        for credit in obj.credits])
1649
1650    def get_units_claimed(self, row, case_quantity=None):
1651        """
1652        Returns the total number of units which are "claimed" by child rows,
1653        for the given truck dump parent row.
1654        """
1655        claimed = 0
1656        for claim in row.claims:
1657            # prefer child row's notion of case quantity, over parent row
1658            case_qty = case_quantity or claim.claiming_row.case_quantity or row.case_quantity
1659            claimed += self.get_units_confirmed(claim, case_quantity=case_qty)
1660        return claimed
1661
1662    def get_units_claimed_received(self, row, case_quantity=None):
1663        return sum([self.get_units_received(claim, case_quantity=row.case_quantity)
1664                    for claim in row.claims])
1665
1666    def get_units_claimed_damaged(self, row, case_quantity=None):
1667        return sum([self.get_units_damaged(claim, case_quantity=row.case_quantity)
1668                    for claim in row.claims])
1669
1670    def get_units_claimed_expired(self, row, case_quantity=None):
1671        return sum([self.get_units_expired(claim, case_quantity=row.case_quantity)
1672                    for claim in row.claims])
1673
1674    def get_units_available(self, row, case_quantity=None):
1675        confirmed = self.get_units_confirmed(row, case_quantity=case_quantity)
1676        claimed = self.get_units_claimed(row, case_quantity=case_quantity)
1677        return confirmed - claimed
1678
1679    def auto_receive_all_items(self, batch, progress=None):
1680        """
1681        Automatically "receive" all items for the given batch.  Meant for
1682        development purposes only!
1683        """
1684        if self.config.production():
1685            raise NotImplementedError("Feature is not meant for production use.")
1686
1687        def receive(row, i):
1688
1689            # auto-receive remaining cases
1690            cases_ordered = row.cases_ordered or 0
1691            cases_confirmed = ((row.cases_received or 0)
1692                               + (row.cases_damaged or 0)
1693                               + (row.cases_expired or 0))
1694            if cases_ordered > cases_confirmed:
1695                row.cases_received = (row.cases_received or 0) + (
1696                    cases_ordered - cases_confirmed)
1697
1698            # auto-receive remaining units
1699            units_ordered = row.units_ordered or 0
1700            units_confirmed = ((row.units_received or 0)
1701                               + (row.units_damaged or 0)
1702                               + (row.units_expired or 0))
1703            if units_ordered > units_confirmed:
1704                row.units_received = (row.units_received or 0) + (
1705                    units_ordered - units_confirmed)
1706
1707            # establish truck dump claims if applicable
1708            if (batch.is_truck_dump_parent()
1709                and batch.truck_dump_children_first
1710                and row.product):
1711                self.make_truck_dump_claims_for_parent_row(row)
1712
1713        self.progress_loop(receive, batch.active_rows(), progress,
1714                           message="Auto-receiving all items")
1715
1716        self.refresh(batch, progress=progress)
1717
1718    def update_order_counts(self, purchase, progress=None):
1719
1720        def update(item, i):
1721            if item.product:
1722                inventory = item.product.inventory or model.ProductInventory(product=item.product)
1723                inventory.on_order = (inventory.on_order or 0) + (item.units_ordered or 0) + (
1724                    (item.cases_ordered or 0) * (item.case_quantity or 1))
1725
1726        self.progress_loop(update, purchase.items, progress,
1727                           message="Updating inventory counts")
1728
1729    def update_receiving_inventory(self, purchase, consume_on_order=True, progress=None):
1730
1731        def update(item, i):
1732            if item.product:
1733                inventory = item.product.inventory or model.ProductInventory(product=item.product)
1734                count = (item.units_received or 0) + (item.cases_received or 0) * (item.case_quantity or 1)
1735                if count:
1736                    if consume_on_order:
1737                        if (inventory.on_order or 0) < count:
1738                            raise RuntimeError("Received {} units for {} but it only had {} on order".format(
1739                                count, item.product, inventory.on_order or 0))
1740                        inventory.on_order -= count
1741                    inventory.on_hand = (inventory.on_hand or 0) + count
1742
1743        self.progress_loop(update, purchase.items, progress,
1744                           message="Updating inventory counts")
1745
1746    def why_not_execute(self, batch):
1747        """
1748        This method should return a string indicating the reason why the given
1749        batch should not be considered executable.  By default it returns
1750        ``None`` which means the batch *is* to be considered executable.
1751
1752        Note that it is assumed the batch has not already been executed, since
1753        execution is globally prevented for such batches.
1754        """
1755        # not all receiving batches are executable
1756        if batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
1757
1758            if batch.is_truck_dump_parent() and batch.truck_dump_status != batch.STATUS_TRUCKDUMP_CLAIMED:
1759                return ("Can't execute a Truck Dump (parent) batch until "
1760                        "it has been fully claimed by children")
1761
1762            if batch.is_truck_dump_child():
1763                return ("Can't directly execute batch which is child of a truck dump "
1764                        "(must execute truck dump instead)")
1765
1766    def execute(self, batch, user, progress=None):
1767        """
1768        Default behavior for executing a purchase batch will create a new
1769        purchase, by invoking :meth:`make_purchase()`.
1770        """
1771        session = orm.object_session(batch)
1772
1773        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
1774            purchase = self.make_purchase(batch, user, progress=progress)
1775            self.update_order_counts(purchase, progress=progress)
1776            return purchase
1777
1778        elif batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
1779            if self.allow_truck_dump and batch.is_truck_dump_parent():
1780                self.execute_truck_dump(batch, user, progress=progress)
1781                return True
1782            else:
1783                with session.no_autoflush:
1784                    return self.receive_purchase(batch, progress=progress)
1785
1786        elif batch.mode == self.enum.PURCHASE_BATCH_MODE_COSTING:
1787            # TODO: finish this...
1788            # with session.no_autoflush:
1789            #     return self.cost_purchase(batch, progress=progress)
1790            purchase = batch.purchase
1791            purchase.invoice_date = batch.invoice_date
1792            purchase.status = self.enum.PURCHASE_STATUS_COSTED
1793            return purchase
1794
1795        assert False
1796
1797    def execute_truck_dump(self, batch, user, progress=None):
1798        now = make_utc()
1799        for child in batch.truck_dump_children:
1800            if not self.execute(child, user, progress=progress):
1801                raise RuntimeError("Failed to execute child batch: {}".format(child))
1802            child.executed = now
1803            child.executed_by = user
1804
1805    def make_credits(self, batch, progress=None):
1806        session = orm.object_session(batch)
1807        mapper = orm.class_mapper(model.PurchaseBatchCredit)
1808
1809        def copy(row, i):
1810            for batch_credit in row.credits:
1811                credit = model.PurchaseCredit()
1812                for prop in mapper.iterate_properties:
1813                    if isinstance(prop, orm.ColumnProperty) and hasattr(credit, prop.key):
1814                        setattr(credit, prop.key, getattr(batch_credit, prop.key))
1815                credit.status = self.enum.PURCHASE_CREDIT_STATUS_NEW
1816                session.add(credit)
1817
1818        return self.progress_loop(copy, batch.active_rows(), progress,
1819                                  message="Creating purchase credits")
1820
1821    def make_purchase(self, batch, user, progress=None):
1822        """
1823        Effectively clones the given batch, creating a new Purchase in the
1824        Rattail system.
1825        """
1826        session = orm.object_session(batch)
1827        purchase = model.Purchase()
1828
1829        # TODO: should be smarter and only copy certain fields here
1830        skip_fields = [
1831            'date_received',
1832        ]
1833        for prop in orm.object_mapper(batch).iterate_properties:
1834            if prop.key in skip_fields:
1835                continue
1836            if hasattr(purchase, prop.key):
1837                setattr(purchase, prop.key, getattr(batch, prop.key))
1838
1839        def clone(row, i):
1840            item = model.PurchaseItem()
1841            # TODO: should be smarter and only copy certain fields here
1842            for prop in orm.object_mapper(row).iterate_properties:
1843                if hasattr(item, prop.key):
1844                    setattr(item, prop.key, getattr(row, prop.key))
1845            purchase.items.append(item)
1846
1847        with session.no_autoflush:
1848            self.progress_loop(clone, batch.active_rows(), progress,
1849                               message="Creating purchase items")
1850
1851        purchase.created = make_utc()
1852        purchase.created_by = user
1853        purchase.status = self.enum.PURCHASE_STATUS_ORDERED
1854        session.add(purchase)
1855        batch.purchase = purchase
1856        return purchase
1857
1858    def receive_purchase(self, batch, progress=None):
1859        """
1860        Update the purchase for the given batch, to indicate received status.
1861        """
1862        session = orm.object_session(batch)
1863        purchase = batch.purchase
1864        if not purchase:
1865            batch.purchase = purchase = model.Purchase()
1866
1867            # TODO: should be smarter and only copy certain fields here
1868            skip_fields = [
1869                'uuid',
1870                'date_received',
1871            ]
1872            with session.no_autoflush:
1873                for prop in orm.object_mapper(batch).iterate_properties:
1874                    if prop.key in skip_fields:
1875                        continue
1876                    if hasattr(purchase, prop.key):
1877                        setattr(purchase, prop.key, getattr(batch, prop.key))
1878
1879        purchase.invoice_number = batch.invoice_number
1880        purchase.invoice_date = batch.invoice_date
1881        purchase.invoice_total = batch.invoice_total
1882        purchase.date_received = batch.date_received
1883
1884        # determine which fields we'll copy when creating new purchase item
1885        copy_fields = []
1886        for prop in orm.class_mapper(model.PurchaseItem).iterate_properties:
1887            if hasattr(model.PurchaseBatchRow, prop.key):
1888                copy_fields.append(prop.key)
1889
1890        def update(row, i):
1891            item = row.item
1892            if not item:
1893                row.item = item = model.PurchaseItem()
1894                for field in copy_fields:
1895                    setattr(item, field, getattr(row, field))
1896                purchase.items.append(item)
1897
1898            item.cases_received = row.cases_received
1899            item.units_received = row.units_received
1900            item.cases_damaged = row.cases_damaged
1901            item.units_damaged = row.units_damaged
1902            item.cases_expired = row.cases_expired
1903            item.units_expired = row.units_expired
1904            item.invoice_line_number = row.invoice_line_number
1905            item.invoice_case_cost = row.invoice_case_cost
1906            item.invoice_unit_cost = row.invoice_unit_cost
1907            item.invoice_total = row.invoice_total
1908
1909        with session.no_autoflush:
1910            self.progress_loop(update, batch.active_rows(), progress,
1911                               message="Updating purchase line items")
1912
1913        purchase.status = self.enum.PURCHASE_STATUS_RECEIVED
1914        return purchase
1915
1916    def clone_row(self, oldrow):
1917        newrow = super(PurchaseBatchHandler, self).clone_row(oldrow)
1918
1919        for oldcredit in oldrow.credits:
1920            newcredit = model.PurchaseBatchCredit()
1921            self.copy_credit_attributes(oldcredit, newcredit)
1922            newrow.credits.append(newcredit)
1923
1924        return newrow
1925
1926    def copy_credit_attributes(self, source_credit, target_credit):
1927        mapper = orm.class_mapper(model.PurchaseBatchCredit)
1928        for prop in mapper.iterate_properties:
1929            if prop.key not in ('uuid', 'row_uuid'):
1930                if isinstance(prop, orm.ColumnProperty):
1931                    setattr(target_credit, prop.key, getattr(source_credit, prop.key))
Note: See TracBrowser for help on using the repository browser.