This repository has been archived by the owner on Jun 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
farm_grazing.module
1231 lines (1053 loc) · 44.4 KB
/
farm_grazing.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Farm grazing module.
*/
include_once 'farm_grazing.features.inc';
/**
* Implements hook_farm_ui_entities().
*/
function farm_grazing_farm_ui_entities() {
return array(
'farm_plan' => array(
'grazing' => array(
'label' => t('Grazing Plan'),
'label_plural' => t('Grazing Plans'),
'view' => 'farm_grazing_plan',
),
),
);
}
/**
* Implements hook_farm_asset_property().
*/
function farm_grazing_farm_asset_property() {
$prefix = 'farm_grazing_';
return array(
$prefix . 'animal_type',
$prefix . 'planned_arrival',
$prefix . 'planned_departure',
);
}
/**
* Implements hook_permission().
*/
function farm_grazing_permission() {
$perms = array(
'administer farm_grazing module' => array(
'title' => t('Administer farm grazing module'),
),
);
return $perms;
}
/**
* Implements hook_farm_access_perms().
*/
function farm_grazing_farm_access_perms($role) {
$perms = array();
// Load the list of farm roles.
$roles = farm_access_roles();
// If this role has 'config' access, grant access to grazing configuration.
if (!empty($roles[$role]['access']['config'])) {
$perms[] = 'administer farm_grazing module';
}
return $perms;
}
/**
* Implements hook_menu().
*/
function farm_grazing_menu() {
// A menu entry with tabs.
// For tabs we need at least 3 things:
// 1) A parent MENU_NORMAL_ITEM menu item (examples/menu_example/tabs in this
// example.)
// 2) A primary tab (the one that is active when we land on the base menu).
// This tab is of type MENU_DEFAULT_LOCAL_TASK.
// 3) Some other menu entries for the other tabs, of type MENU_LOCAL_TASK.
// Getting Started.
// Planning Factors.
// Are both handled as part of the grazing_plan entity
// Paddocks.
// This has sub menu items that deal with paddocks
$items['farm/plan/%farm_plan/paddocks'] = array(
'title' => 'Paddocks',
'description' => 'Identify paddocks that should be available for this plan.',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_select_paddocks_form', 2),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'file' => 'farm_grazing.paddocks.select.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 10,
);
// Herds summary.
$items['farm/plan/%farm_plan/herds'] = array(
'title' => 'Herds',
'description' => 'Manage herds in the plan (Select/Add/Combine/Split/Ship)',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_plan_herds_manage_form', 2),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'file' => 'farm_grazing.herds.manage.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 20,
);
// Herd specifics.
$items['farm/plan/%farm_plan/herds/%'] = array(
'title' => 'Herd details',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_plan_herds_detail_form', 2, 4),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'file' => 'farm_grazing.herds.detail.inc',
'type' => MENU_NORMAL_ITEM,
);
// Paddocks - Select
$items['farm/plan/%farm_plan/paddocks/select'] = array(
'title' => 'Select',
'description' => '',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => 10,
);
// Add a new consideration.
$items['farm/plan/%farm_plan/paddocks/exclusions'] = array(
'title' => 'Exclusions',
'description' => 'Define exclusion periods for paddocks.',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_plan_consideration_form', 2),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'type' => MENU_LOCAL_TASK,
'weight' => 20,
);
// Paddocks - productivity.
$items['farm/plan/%farm_plan/paddocks/productivity'] = array(
'title' => 'Productivity',
'description' => 'Set productivity for each paddock.',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_plan_productivity_form', 2),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'file' => 'farm_grazing.paddocks.productivity.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 30,
);
// Paddocks - Recovery.
$items['farm/plan/%farm_plan/paddocks/recovery'] = array(
'title' => 'Recovery',
'description' => 'Set min and max recovery periods for paddocks.',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_plan_recovery_form', 2),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'file' => 'farm_grazing.paddocks.recovery.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 40,
);
// Paddocks - Summary.
$items['farm/plan/%farm_plan/paddocks/summary'] = array(
'title' => 'Summary',
'description' => 'Review summary information about paddocks.',
'page callback' => 'farm_grazing_plan_summary_page',
'page arguments' => array(2),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'file' => 'farm_grazing.paddocks.summary.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 50,
);
// Herds - Management
$items['farm/plan/%farm_plan/herds/manage'] = array(
'title' => 'Manage',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => 10,
);
$items['farm/plan/%farm_plan/herds/%/remove'] = array(
'title' => 'Remove Herd From Plan',
'description' => 'This herd will be removed from the plan',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_plan_herd_remove_form', 2, 4),
'access arguments' => array('edit any grazing farm plans'),
'file' => 'farm_grazing.herds.manage.inc',
'type' => MENU_CALLBACK,
);
// Herds - Historical grazing patterns.
$items['farm/plan/%farm_plan/herds/history'] = array(
'title' => 'History',
'description' => 'Review historical grazing patterns',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_plan_history_form', 2),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'file' => 'farm_grazing.herds.history.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 30,
);
// Herds - Rotations.
$items['farm/plan/%farm_plan/herds/rotations'] = array(
'title' => 'Rotations',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_plan_rotations_form', 2),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(2),
'file' => 'farm_grazing.herds.rotations.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 40,
);
// Rotation delete callback.
$items['farm/plan/%farm_plan/herds/rotations/%/delete'] = array(
'title' => 'Paddocks',
'description' => 'Remove paddock from herd rotations.',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_plan_rotation_delete_form', 2, 5),
'access arguments' => array('edit any grazing farm plans'),
'file' => 'farm_grazing.herds.rotations.inc',
'type' => MENU_CALLBACK,
);
// Callback for generating a paddock rotation image.
// Arguments are:
// 3: farm plan
// 5: paddock ID
// 6: start timestamp
// 7: end timestamp
$items['farm/grazing/plan/%farm_plan/plot/%/%/%'] = array(
'page callback' => 'farm_grazing_plan_plot',
'page arguments' => array(3, 5, 6, 7),
'access callback' => 'farm_grazing_plan_access',
'access arguments' => array(3),
'file' => 'farm_grazing.herds.rotations.plot.inc',
'type' => MENU_CALLBACK,
);
// Animal type configuration.
$items['admin/config/farm/grazing_animal_types'] = array(
'title' => 'Grazing animal types',
'description' => 'Manage animal types used in the grazing planning process.',
'page callback' => 'drupal_get_form',
'page arguments' => array('farm_grazing_config_animal_types_form'),
'access arguments' => array('administer farm_grazing module'),
'file' => 'farm_grazing.admin.inc',
);
return $items;
}
/**
* Access callback function for grazing plan pages.
*/
function farm_grazing_plan_access($plan, $account = NULL) {
// If the plan is not a grazing plan, deny access.
if ($plan->type != 'grazing') {
return FALSE;
}
// Otherwise, check to see if the user has access to edit grazing plans.
return user_access('edit any grazing farm plans', $account);
}
/**
* Implements hook_feeds_importer_default_alter().
*/
function farm_grazing_feeds_importer_default_alter($importers) {
// Add extra field mappings to animals for grazing properties.
$name = 'farm_asset_animal';
if (!empty($importers[$name])) {
$mappings = array(
array(
'source' => 'Grazing animal type',
'target' => 'farm_asset_property:farm_grazing_animal_type',
'unique' => FALSE,
'language' => 'und',
),
array(
'source' => 'Planned arrival',
'target' => 'farm_asset_property:farm_grazing_planned_arrival',
'unique' => FALSE,
'language' => 'und',
),
array(
'source' => 'Planned departure',
'target' => 'farm_asset_property:farm_grazing_planned_departure',
'unique' => FALSE,
'language' => 'und',
),
);
$importer_mappings =& $importers[$name]->config['processor']['config']['mappings'];
$importer_mappings = array_merge($importer_mappings, $mappings);
}
}
/**
* Implements hook_feeds_tamper_default_alter().
*/
function farm_grazing_feeds_tamper_default_alter(&$feeds_tampers) {
// If farm_import is not installed, bail.
if (!module_exists('farm_import')) {
return;
}
// Check that animal type is an allowed value.
/**
* @todo
* Needs allowed_value plugin.
*/
// $feeds_tamper = farm_import_feeds_tamper_plugin('farm_asset', 'animal', 'Grazing animal type', 'allowed_value');
// $feeds_tampers[$feeds_tamper->id] = $feeds_tamper;
// Convert planned arrival to a Unix timestamp.
$feeds_tamper = farm_import_feeds_tamper_plugin('farm_asset', 'animal', 'Planned arrival', 'strtotime');
$feeds_tamper->weight = 1;
$feeds_tampers[$feeds_tamper->id] = $feeds_tamper;
// Convert planned arrival back to a date formatted for the grazing module.
$feeds_tamper = farm_import_feeds_tamper_plugin('farm_asset', 'animal', 'Planned arrival', 'timetodate');
$feeds_tamper->settings['date_format'] = 'Y-m-d';
$feeds_tamper->weight = 2;
$feeds_tampers[$feeds_tamper->id] = $feeds_tamper;
// Convert planned departure to a Unix timestamp.
$feeds_tamper = farm_import_feeds_tamper_plugin('farm_asset', 'animal', 'Planned departure', 'strtotime');
$feeds_tamper->weight = 1;
$feeds_tampers[$feeds_tamper->id] = $feeds_tamper;
// Convert planned departure back to a date formatted for the grazing module.
$feeds_tamper = farm_import_feeds_tamper_plugin('farm_asset', 'animal', 'Planned departure', 'timetodate');
$feeds_tamper->settings['date_format'] = 'Y-m-d';
$feeds_tamper->weight = 2;
$feeds_tampers[$feeds_tamper->id] = $feeds_tamper;
}
/**
* Implements hook_farm_plan_consideration_types().
*/
function farm_grazing_farm_plan_consideration_types() {
return array(
'farm_grazing_exclusion' => array(
'label' => t('Paddock exclusion'),
'color' => 'orange',
),
);
}
/**
* Load an array of grazing plan options.
*/
function farm_grazing_plan_options() {
// Start with an empty array.
$plan_options = array();
// Query the database for plans.
$query = db_query("SELECT id, name FROM {farm_plan} WHERE type = 'grazing' AND active = 1");
// Build a list of plan options.
$records = $query->fetchAll();
foreach ($records as $record) {
$plan_options[$record->id] = $record->name;
}
// Return the options array.
return $plan_options;
}
/**
* Load an array of animal types.
*
* @return array
* Returns an array of animal types.
*/
function farm_grazing_animal_types() {
$types = array();
$result = db_query('SELECT * FROM farm_grazing_animal_types ORDER BY name DESC');
foreach ($result as $record) {
if (!empty($record->type_id)) {
$types[$record->type_id] = (array) $record;
}
}
return $types;
}
/**
* Generate a list of animal type options for use in Form API.
*
* @return array
* Returns an array of options.
*/
function farm_grazing_animal_type_options() {
$animal_type_options = array();
$animal_types = farm_grazing_animal_types();
$animal_type_options = array('');
foreach ($animal_types as $animal_type) {
$animal_type_options[$animal_type['type_id']] = $animal_type['name'];
}
return $animal_type_options;
}
/**
* Implements hook_entity_view_alter().
*/
function farm_grazing_entity_view_alter(&$build, $type) {
// If it's not a farm_asset, or if the entity object is not available, bail.
if ($type != 'farm_asset' || empty($build['#entity'])) {
return;
}
// Alias the asset variable.
$asset = $build['#entity'];
// If it isn't an animal asset, bail.
if ($asset->type != 'animal') {
return;
}
// Start an empty output string.
$output = '';
// Define the properties we care about.
$properties = array(
'animal_type',
'planned_arrival',
'planned_departure',
);
// Iterate through the properties.
foreach ($properties as $name) {
// Load the property.
$property = farm_asset_property_get($asset->id, 'farm_grazing_' . $name);
// If it doesn't exist, skip it.
if (empty($property)) {
continue;
}
// Add output based on the property.
$label = '';
$value = '';
switch ($name) {
case 'animal_type':
$types = farm_grazing_animal_types();
if (!empty($types[$property]['name'])) {
$label = t('Grazing animal type');
$value = $types[$property]['name'];
}
break;
case 'planned_arrival':
$label = t('Planned arrival');
$value = date('Y-m-d', $property);
break;
case 'planned_departure':
$label = t('Planned departure');
$value = date('Y-m-d', $property);
break;
}
// If a label and value are available, add it to the output.
if (!empty($label) && !empty($value)) {
$output .= '<div><strong>' . $label . ': </strong> ' . $value . '</div>';
}
}
// If there is output, add it to the build array.
if (!empty($output)) {
$build['grazing_properties'] = array(
'#markup' => $output,
'#prefix' => '<div class="grazing-properties">',
'#suffix' => '</div>',
'#weight' => 100,
);
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function farm_grazing_form_farm_asset_form_alter(&$form, &$form_state, $form_id) {
// Get the farm asset entity from the form.
$asset = $form['farm_asset']['#value'];
// If the asset is not an animal, bail.
if (empty($asset->type) || $asset->type != 'animal') {
return;
}
// Add a "Grazing" fieldset.
$form['farm_grazing'] = array(
'#type' => 'fieldset',
'#title' => t('Grazing'),
'#description' => t('If this animal is used in a grazing plan, the following information is required for plan calculations.'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#weight' => 100,
);
// Get a list of animal type options.
$animal_type_options = farm_grazing_animal_type_options();
// Animal type dropdown.
$form['farm_grazing']['farm_grazing_animal_type'] = array(
'#type' => 'select',
'#title' => t('Animal type'),
'#description' => t('Select the type of animal that this @asset_type represents. This will determine the dry-matter intake requirements for this @asset_type.', array('@asset_type' => $asset->type)),
'#options' => $animal_type_options,
'#default_value' => farm_asset_property_get($asset->id, 'farm_grazing_animal_type'),
);
// Planned arrival date.
$planned_arrival = farm_asset_property_get($asset->id, 'farm_grazing_planned_arrival');
$form['farm_grazing']['farm_grazing_planned_arrival'] = array(
'#type' => 'date_select',
'#title' => t('Planned arrival date'),
'#default_value' => !empty($planned_arrival) ? date('Y-m-d', $planned_arrival) : NULL,
'#date_format' => 'Y-m-d',
'#date_label_position' => 'within',
'#date_year_range' => '-3:+10',
);
// Planned departure date.
$planned_departure = farm_asset_property_get($asset->id, 'farm_grazing_planned_departure');
$form['farm_grazing']['farm_grazing_planned_departure'] = array(
'#type' => 'date_select',
'#title' => t('Planned departure date'),
'#default_value' => !empty($planned_departure) ? date('Y-m-d', $planned_departure) : NULL,
'#date_format' => 'Y-m-d',
'#date_label_position' => 'within',
'#date_year_range' => '-3:+10',
);
// Add a submit handler.
$form['actions']['submit']['#submit'][] = 'farm_grazing_asset_form_submit';
// Add to the "General" group.
$form['#group_children']['farm_grazing'] = 'group_farm_general';
}
/**
* Submit handler for saving grazing properties of an asset.
*
* @param array $form
* The form array.
* @param array $form_state
* The form state array.
*/
function farm_grazing_asset_form_submit(array $form, array &$form_state) {
// If an asset doesn't exist, bail.
if (empty($form_state['values']['farm_asset'])) {
return;
}
// Grab the asset.
$asset = $form_state['values']['farm_asset'];
// Set asset properties.
$properties = array(
'farm_grazing_animal_type',
'farm_grazing_planned_arrival',
'farm_grazing_planned_departure',
);
foreach ($properties as $name) {
if (!empty($form_state['values'][$name])) {
// Convert arrival and departure dates to a timestamp.
if (in_array($name, array('farm_grazing_planned_arrival', 'farm_grazing_planned_departure'))) {
$form_state['values'][$name] = strtotime($form_state['values'][$name]);
}
// Save the asset property.
farm_asset_property_set($asset->id, $name, $form_state['values'][$name]);
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function farm_grazing_form_log_form_alter(&$form, &$form_state, $form_id) {
// Add our grazing validation function to log forms.
$form['#validate'][] = 'farm_grazing_log_form_validate';
}
/**
* Validation function for log forms.
*/
function farm_grazing_log_form_validate(&$form, &$form_state) {
// If a log ID doesn't exist, bail.
if (empty($form_state['values']['log']->id)) {
return;
}
// Check to see if this log is managed by a grazing plan.
$managed = db_query('SELECT COUNT(*) FROM {farm_grazing_rotations} WHERE log_id = :log_id', array(':log_id' => $form_state['values']['log']->id))->fetchField();
// If the log isn't managed, we don't care about it.
if (empty($managed)) {
return;
}
// If the log doesn't have a movement location, we don't care about it.
if (empty($form['field_farm_movement'][LANGUAGE_NONE][0]['field_farm_move_to'][LANGUAGE_NONE]['#default_value'][0])) {
return;
}
// Prevent the movement field from being changed.
if ($form['field_farm_movement'][LANGUAGE_NONE][0]['field_farm_move_to'][LANGUAGE_NONE]['#default_value'][0] != $form_state['values']['field_farm_movement'][LANGUAGE_NONE][0]['field_farm_move_to'][LANGUAGE_NONE][0]['tid']) {
form_set_error('field_farm_movement', t('You cannot change the location of this movement log, because it is managed by one or more <a href="@grazing_plans">grazing plans</a>.', array('@grazing_plans' => url('farm/plans/grazing'))));
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function farm_grazing_form_farm_plan_consideration_form_alter(&$form, &$form_state, $form_id) {
// Get the consideration from the form (bail if it doesn't exist).
if (empty($form['consideration']['#value'])) {
return;
}
$consideration = $form['consideration']['#value'];
// If this is not a grazing plan, do not alter the form.
if (empty($form['plan']['#value']->type) || $form['plan']['#value']->type != 'grazing') {
return;
}
// If this is the /paddocks/exclusions path, default the consideration type
// to 'farm_grazing_exclusion'.
if (arg(3) == 'paddocks' && arg(4) == 'exclusions') {
$form['type']['#default_value'] = 'farm_grazing_exclusion';
$consideration->type = 'farm_grazing_exclusion';
}
// Determine the consideration type, either from the consideration itself, or
// from the form fields.
$consideration_type = !empty($form_state['values']['type']) ? $form_state['values']['type'] : $consideration->type;
// Add a field for associating this consideration with one or more paddocks.
$exclusion_types = array(
'farm_grazing_exclusion',
'concern',
'urgent',
);
if (in_array($consideration_type, $exclusion_types)) {
// Load all paddocks and generate an options list.
$paddocks = farm_area_load_areas('paddock', 'name');
$paddock_options = array();
foreach ($paddocks as $paddock) {
$paddock_options[$paddock->tid] = $paddock->name;
}
// Determine if paddocks have already been selected for this consideration,
// and use them as the default value.
$default_paddock_ids = array();
if (!empty($consideration->entities['taxonomy_term'])) {
foreach ($consideration->entities['taxonomy_term'] as $id) {
$term = taxonomy_term_load($id);
if ($term->vocabulary_machine_name == 'farm_areas') {
if (!empty($term->field_farm_area_type) && $term->field_farm_area_type[LANGUAGE_NONE][0]['value'] == 'paddock') {
$default_paddock_ids[] = $id;
}
}
}
}
// Add a paddock selection field to the form.
$form['extra']['paddock_ids'] = array(
'#type' => 'checkboxes',
'#title' => t('Paddocks'),
'#description' => t('Select the paddocks that this consideration is associated with, in the context of grazing plans.'),
'#options' => $paddock_options,
'#default_value' => $default_paddock_ids,
);
// This is only required if the consideration type is
// 'farm_grazing_exclusion'.
if ($consideration_type == 'farm_grazing_exclusion') {
$form['extra']['paddock_ids']['#required'] = TRUE;
}
// Add our submit function.
$form['#submit'][] = 'farm_grazing_consideration_form_submit';
}
}
/**
* Consideration form submit function.
*/
function farm_grazing_consideration_form_submit(&$form, &$form_state) {
// If paddock IDs were set, then save them to the consideration.
if (!empty($form_state['values']['paddock_ids']) && !empty($form_state['values']['consideration'])) {
// Get the consideration and paddock IDs from the form.
$consideration = $form_state['values']['consideration'];
$paddock_ids = $form_state['values']['paddock_ids'];
// Initialize the taxonomy_term array if it isn't already.
if (!isset($consideration->entities['taxonomy_term'])) {
$consideration->entities['taxonomy_term'] = array();
}
// Get the original paddock IDs from the form's default value.
$old_paddock_ids = array();
if (!empty($form['extra']['paddock_ids']['#default_value'])) {
$old_paddock_ids = $form['extra']['paddock_ids']['#default_value'];
}
// Filter out unselected paddocks.
$paddock_ids = array_filter($paddock_ids);
// Compare the old paddock IDs to the new ones, so we can determine if we
// need to keep, remove, or add any in the database.
$remove = array_diff($old_paddock_ids, $paddock_ids);
$add = array_diff($paddock_ids, $old_paddock_ids);
// Remove old paddock associations.
if (!empty($remove)) {
foreach ($consideration->entities['taxonomy_term'] as $key => $value) {
if (in_array($value, $remove)) {
unset($consideration->entities['taxonomy_term'][$key]);
}
}
}
// Add new paddock associations.
if (!empty($add)) {
foreach ($add as $paddock_id) {
$consideration->entities['taxonomy_term'][] = $paddock_id;
}
}
// Save the consideration.
farm_plan_consideration_save($consideration);
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function farm_grazing_form_farm_livestock_birth_form_alter(&$form, &$form_state, $form_id) {
// Add an animal type select field to each child in the birth quick form.
$animal_type_options = farm_grazing_animal_type_options();
$child_elements = element_children($form['birth']['child']);
foreach ($child_elements as $child) {
$child_form =& $form['birth']['child'][$child];
$child_form['farm_grazing_animal_type'] = array(
'#type' => 'select',
'#title' => t('Animal type'),
'#description' => t('Select the type of animal for grazing purposes. This will determine the dry-matter intake requirements for this animal.'),
'#options' => $animal_type_options,
);
}
$form['#submit'][] = 'farm_grazing_birth_form_submit';
}
/**
* Birth quick form submit function.
*/
function farm_grazing_birth_form_submit(&$form, &$form_state) {
// If there are children stored in $form_state['storage'], iterate through
// them and save their animal types (if set).
if (!empty($form_state['storage']['children'])) {
foreach ($form_state['storage']['children'] as $key => $child) {
if (empty($child->id)) {
continue;
}
if (empty($form_state['values']['birth']['child'][$key]['farm_grazing_animal_type'])) {
continue;
}
farm_asset_property_set($child->id, 'farm_grazing_animal_type', $form_state['values']['birth']['child'][$key]['farm_grazing_animal_type']);
}
}
}
/**
* Implements hook_entity_view().
*/
function farm_grazing_entity_view($entity, $type, $view_mode, $langcode) {
// If the entity is not a grazing plan, bail.
if (!($type == 'farm_plan' && $entity->type == 'grazing')) {
return;
}
module_load_include('inc', 'farm_grazing', 'farm_grazing.plan.dashboard');
$entity->content['content'] = drupal_get_form('farm_grazing_plan_dashboard_form', $entity);
$entity->content['content']['#weight'] = 100;
}
/**
* Implements hook_theme
*/
function farm_grazing_theme() {
return array(
'farm_grazing_paddocks_productivity' => array(
// The renderable element is the form.
'render element' => 'form',
'file' => 'farm_grazing.paddocks.productivity.inc',
),
'farm_grazing_paddocks_recovery' => array(
'render element' => 'form',
'file' => 'farm_grazing.paddocks.recovery.inc',
),
'farm_grazing_plan_herds_manage_form' => array(
'render element' => 'form',
'file' => 'farm_grazing.herds.manage.inc',
),
'farm_grazing_plan_herds_detail_form' => array(
'render element' => 'form',
'file' => 'farm_grazing.herds.detail.inc',
),
'farm_grazing_plan_rotations_form' => array(
'render element' => 'form',
'file' => 'farm_grazing.herds.rotations.inc',
),
'farm_grazing_config_animal_types_form' => array(
'render element' => 'form',
'file' => 'farm_grazing.admin.inc',
),
'farm_grazing_plan_dashboard_form' => array(
'render element' => 'form',
'file' => 'farm_grazing.plan.dashboard.inc',
),
);
}
/**
* Implements hook_help().
*/
function farm_grazing_help($path, $arg) {
// If the path is /farm/plans/grazing, show general help text about grazing
// plans.
if ($path == 'farm/plans/grazing') {
return '<p>' . t('Select an existing plan or create a new plan.') .
'</p><p>' . t('The planning factors are an important part of building your plan. You can edit these by clicking the "Edit" tab at any time. Read the description under the form field for "Planning factors".') . '</p>';
}
// Or, if the path starts with 'farm/plan/%', then load the plan and see if
// it is a grazing plan. If not, bail. Otherwise continue.
if (strpos($path, 'farm/plan/%') === 0) {
$plan = farm_plan_load($arg[2]);
if (empty($plan) || $plan->type != 'grazing') {
return '';
}
}
// Add help text to all farm/plan/% paths.
switch ($path) {
case 'farm/plan/%':
case 'farm/plan/%/view':
return '<p>' . t('Open/Close each of the sections below, "Getting Started", "Management Concerns", and Implementing the plan", by clicking on the section title.') . '</p>';
case 'farm/plan/%/paddocks':
case 'farm/plan/%/paddocks/default':
return '<p>' . t('Define your paddocks in the') . ' <a href="' . base_path() . 'farm/areas">Areas</a> ' . t('tab above. Select which paddocks you want available for use in this plan here and then use tabs "Exclusions", "Productivity", "Recovery" and "Summary" to add additional information about your paddocks.') . '</p>';
case 'farm/plan/%/paddocks/exclusions':
return '<p>' . t('Enter dates when a paddock can not under any circumstances have a herd on it. Also enter dates for paddocks that need special attention and why. For example: sacrificial paddocks where you plan to run some animals on continuous graze, bare, eroding ground that needs healing, areas you want to rest for brush cover for wildlife, areas where you need to remove forage for fire protection, paddocks you plan to strip graze, and other considerations.') . '</p>';
case 'farm/plan/%/paddocks/productivity':
return '<p>' . t('For Forage Quality, you should enter ADA/H for each paddock, or rate it 1-10.') .
'</p><p>' . t('Est. Relative Quality is the estimated animals days for the paddock based on Forage Quality if you entered a value in ADA/H, but if you entered a rating, then the number will be a relative ranking of the amount of forage each paddock can give relative to the other paddocks.') . '</p>';
case 'farm/plan/%/paddocks/recovery':
return '<p>' . t('Enter your minimum and maximum recovery periods (in days) for each planned month. Unless you have a great many paddocks per herd and can safely choose a single recovery period, you will have to determine the expected plant recovery period under fast growth conditions and the expected plant recovery period under slow growth conditions.') .
'</p><p>' . t('If you have not defined any herds yet, we assume one herd. This page will automatically adjust for multiple herds once you define them, so check back once you have defined herds.') . '</p>';
case 'farm/plan/%/paddocks/summary':
return '<p>' . t('Use the Check Min/Max Recovery Period below and if any recovery period is much too short, you must add days to the minimum grazing periods in other paddocks that can absorb them. Follow the same procedure for maximum grazing periods, though the problems will probably be less critical if you can\'t make complete adjustments.') . '</p>';
case 'farm/plan/%/herds':
case 'farm/plan/%/herds/default':
return '<p>' . t('A herd is defined as a group of animals that will be rotated between paddock to together regardless of the make up of animals in the herd.') .
'</p><p>' . t('Most smaller ranches will only have a single herd as you will need more paddocks to support multiple herds and allow for adequate recovery periods of the paddocks.') .
'</p><p>' . t('If you are new to this planning method or you have a smaller ranch, try to keep your plan simple to start with and built it based on a single herd.') .
'</p><p>' . t('You can define animals ') . '<a href="' . base_path() . 'farm/asset/add/animal?destination=farm/assets/animals" target="_new">' . t('HERE') . '</a> ' . t(' and assign them to a group. You will need to enter all of the following fields:') . '<ul>' .
'<li>' . t('Name') . '</li>' .
'<li>' . t('Species/breed') . '</li>' .
'<li>' . t('Description (optional)') . '</li>' .
'<li>' . t('Location (optional)') . '</li>' .
'<li>' . t('Weight') . '</li>' .
'<li>' . t('Grazing') . '</li>' .
'<ul>' .
'<li>' . t('Animal type - ') . l(t('Manage animal types'), 'admin/config/farm/grazing_animal_types', array('query' => array('destination' => current_path()))) . '</li>' .
'<li>' . t('Planned arrival date') . '</li>' .
'<li>' . t('Planned departure date') . '</li>' .
'</ul>' .
'<li>' . t('Group membership (Herd name)') . '</li>' .
'<ul>' .
'<li>' . t('Select an existing group (Herd)') . '</li>' .
'<li>' . t('or Create a new group (Herd)') . '</li>' .
'</ul>' .
'<li>' . t('Inventory (Head count)') . '</li>' .
'</ul>' .
'</p>';
case 'farm/plan/%/herds/paddocks':
return '<p>' . t('Add or remove paddocks from each herd in your plan. In the next two steps you will review the historical grazing patterns and then order the paddock rotations for each herd.') . '</p>';
case 'farm/plan/%/herds/history':
return '<p>' . t('Skip this step if this is your first grazing plan. Otherwise, check paddock by paddock over previous grazing charts for evidence of inappropriate heavy use of individual paddocks, repeated early or late season use of particular paddocks, or of paddocks that failed to receive adequate recovery time in the recent past. If paddocks were marked as heavily grazed, especially early or late in the season last year, exclude them in the early and late growing season this year to avoid repetition.') .
'</p><p>' . t('This table counts the frequency of historical use in the given months. Ideally one would like to have these numbers consistent across the months in the plan over the long term. In the short term avoid reuse at start or end of the growing season. Also if a paddock has been used a lot in a given month then avoid using that month also.') .
'</p>';
case 'farm/plan/%/herds/rotations':
return '<p>' . t('Start by adding rotations for each herd. Select the herd you would like to rotate, and one or more paddocks to rotate through. After you have created some rotations, you can reorder the paddocks by moving them up or down in the list. The calendar has various planning events plotted on it, including grazing periods, recovery periods, and planning considerations that you entered earlier. The green is where that paddock will get grazed.') .
'</p><p>' . t('You should also look back at the Herds/History tab to avoid bad patterns like repetitive grazing of the the same paddock at the start or end of a season or is getting more heavily used than others.') .
'</p><p>' . t('Purple sections are where there are management events and orange areas indicate average paddock recovery time frames.') .
'</p>';
case 'farm/plan/%/implement':
case 'farm/plan/%/implement/default':
return '<p>' . t('TODO') . '</p>';
}
}
/**
* Implements hook_entity_update().
*/
function farm_grazing_entity_update($entity, $type) {
// Audit asset updates.
if ($type == 'farm_asset') {
farm_grazing_plan_asset_update($entity);
}
// Audit log updates.
elseif ($type == 'log') {
farm_grazing_plan_log_update($entity);
}
}
/**
* Perform checks to see if a group/animal asset is part of a plan, and if
* updating/deleting it will affect that plan.
*
* @param $asset
* The asset that was updated/deleted.
*/
function farm_grazing_plan_asset_update($asset) {
// We only care about group and animal assets.
if (!($asset->type == 'group' || $asset->type == 'animal')) {
return;
}
/**
* @todo
* Perform logic to see if this asset is part of a plan, and whether or not
* editing/deleting this asset will affect the plan.
*
* But for now... just show a message.
*/
drupal_set_message(t('If this asset is part of a grazing plan, you should check to see if your change affects that plan.'), 'warning');
}
/**
* Perform checks to see if a log is part of a plan, and if updating it will
* affect that plan.
*
* @param $log
* The log that was updated.
*/
function farm_grazing_plan_log_update($log) {
// If rotations are being recalculated, do not run the logic in this
// function. This flag is set by the farm_grazing_recalculate_rotations()
// function, to prevent an infinite loop, because it will call log_save()
// which will end up running this code.
if (!empty($log->recalculating_rotations)) {
return;