class DealFormerUseForm(BaseForm): form_title = _('Former use') tg_land_owner = TitleField( required=False, label="", initial=_("Former land owner (not by constitution)") ) land_owner = forms.MultipleChoiceField( required=False, label=_("Former land owner"), choices=( (10, _("State")), (20, _("Private (smallholders)")), (30, _("Private (large-scale)")), (40, _("Community")), (50, _("Other")), ), widget=forms.CheckboxSelectMultiple ) tg_land_owner_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) tg_land_use = TitleField( required=False, label="", initial=_("Former land use") ) land_use = forms.MultipleChoiceField( required=False, label=_("Former land use"), choices=( (10, _("Commercial (large-scale) agriculture")), (20, _("Smallholder agriculture")), (30, _("Shifting cultivation")), (40, _("Pastoralism")), (50, _("Hunting/Gathering")), (60, _("Forestry")), (70, _("Conservation")), (80, _("Other")), ), widget=forms.CheckboxSelectMultiple ) tg_land_use_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) tg_land_cover = TitleField( required=False, label="", initial=_("Former land cover") ) land_cover = forms.MultipleChoiceField( required=False, label=_("Former land cover"), choices=( (10, _("Cropland")), (20, _("Forest land")), (30, _("Pasture")), (40, _("Shrub land/Grassland (Rangeland)")), (50, _("Marginal land")), (60, _("Wetland")), (70, _("Other land[e.g. developed land – specify in comment field]")), ), widget=forms.CheckboxSelectMultiple ) tg_land_cover_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) class Meta: name = 'former_use'
class ChangeDealOverallCommentForm(BaseForm): form_title = _('Overall Comment') # Coordinators and reviewers overall comments tg_overall = TitleField(required=False, label="", initial=_("Overall comment")) tg_overall_comment = forms.CharField(required=False, label="", widget=CommentInput) @classmethod def get_data(cls, deal, tg=None, prefix=""): from inspect import currentframe, getframeinfo data = super().get_data(deal, tg, prefix) if False: comments = Comment.objects.filter( fk_a_tag_group__fk_activity=deal.id, fk_a_tag_group__fk_a_tag__fk_a_value__value="overall" ).order_by("-timestamp") else: frameinfo = getframeinfo(currentframe()) print('*** comments not yet implemented! ', frameinfo.filename, frameinfo.lineno) comments = None if comments and len(comments) > 0: data["tg_overall_comment"] = comments[0].comment return data class Meta: name = 'overall_comment'
class PublicUserInformationForm(AddDealOverallCommentForm): tg_public_user = TitleField(required=False, label="", initial=_("User information")) tg_public_user_comment = forms.CharField( required=True, label="", help_text=_("Write something about yourself and your company. This won't be published"), widget=CommentInput ) public_user_name = forms.CharField(required=False, label=_("Name")) public_user_email = forms.EmailField(required=False, label=_("Email")) public_user_phone = forms.CharField(required=False, label=_("Phone")) # TODO: fix # captcha = ReCaptchaField() class Meta: exclude = ("tg_overall", "tg_overall_comment") def get_action_comment(self): action_comment = "" taggroups = super(PublicUserInformationForm, self).get_attributes() if len(taggroups) > 0: taggroup = taggroups[0] action_comment += "comment: %s\n" % taggroup.get("comment", "-") for t in taggroup.get("tags", []): action_comment += "%s: %s\n" % (t.get("key").split("_")[-1], t.get("value")) return action_comment def get_attributes(self, request=None): return []
class DealSpatialForm(BaseForm): form_title = _('Location') tg_location = TitleField(required=False, label="", initial=_("Location")) level_of_accuracy = forms.TypedChoiceField( required=False, label=_("Spatial accuracy level"), choices=( (0, _("---------")), (10, _("Country")), (30, _("Administrative region")), (30, _("Approximate location")), (40, _("Exact location")), (50, _("Coordinates")), ), coerce=int) location = forms.CharField(required=False, label=_("Location"), widget=LocationWidget) point_lat = forms.CharField(required=False, label=_("Latitude"), widget=forms.TextInput, initial="") point_lon = forms.CharField(required=False, label=_("Longitude"), widget=forms.TextInput, initial="") facility_name = forms.CharField(required=False, label=_("Facility name"), widget=forms.TextInput, initial="") target_country = CountryField(required=False, label=_("Target Country")) target_region = forms.ModelChoiceField( required=False, label=_("Target Region"), widget=forms.HiddenInput, queryset=Region.objects.all().order_by("name")) location_description = forms.CharField(required=False, label=_("Location description"), widget=forms.TextInput, initial="") tg_location_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) class Meta: name = 'spatial_data' def get_attributes(self, request=None): attributes = super().get_attributes() if 'target_country' in attributes \ and not isinstance(attributes['target_country'], int) \ and not attributes['target_country'].isnumeric(): target_country = Country.objects.get( name=attributes['target_country']) attributes['target_country'] = target_country.pk return attributes
class GermanyForm(BaseForm): form_title = _('Germany') tg_land_area = TitleField(required=False, label="", initial=_("Land area")) intended_size = forms.IntegerField(required=False, label=_("Intended size"), help_text=_("ha"), widget=NumberInput) test_integer = forms.IntegerField(required=False, label=_("Test integer"), widget=NumberInput) class Meta: name = 'germany specific info'
class ManageDealForm(BaseForm): tg_action = TitleField(required=False, label="", initial=_("Action comment")) tg_action_comment = forms.CharField(required=False, label="", widget=CommentInput) def __init__(self, *args, **kwargs): if "instance" in kwargs: kwargs.pop("instance") super(ManageDealForm, self).__init__(*args, **kwargs) def save(self): return self
class AddDealEmploymentForm(BaseForm): form_title = _('Employment') # Total number of jobs created tg_total_number_of_jobs_created = TitleField(required=False, label="", initial=_("Number of total jobs created")) total_jobs_created = forms.BooleanField(required=False, label=_("Total number of jobs created")) total_jobs_planned = forms.IntegerField(required=False, label=_("Planned total number of jobs"), help_text=_("jobs"), widget=NumberInput) total_jobs_planned_employees = forms.IntegerField(required=False, label=_("Employees"), help_text=_("employees"), widget=NumberInput) total_jobs_planned_daily_workers = forms.IntegerField(required=False, label=_("Daily/seasonal workers"), help_text=_("workers"), widget=NumberInput) total_jobs_current = YearBasedIntegerField(required=False, label=_("Current total number of jobs"), help_text=_("jobs"), widget=NumberInput) total_jobs_current_employees = YearBasedIntegerField(required=False, label=_("Current total employees"), help_text=_("employees"), widget=NumberInput) total_jobs_current_daily_workers = YearBasedIntegerField(required=False, label=_("Daily/seasonal workers"), help_text=_("workers"), widget=NumberInput) tg_total_number_of_jobs_created_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) # Number of jobs for foreigners created tg_foreign_jobs_created = TitleField(required=False, label="", initial=_("Number of jobs for foreigners created")) foreign_jobs_created = forms.BooleanField(required=False, label=_("Number of jobs for foreigners created")) foreign_jobs_planned = forms.IntegerField(required=False, label=_("Planned number of jobs for foreigners"), help_text=_("jobs"), widget=NumberInput) foreign_jobs_planned_employees = forms.IntegerField(required=False, label=_("Employees"), help_text=_("employees"), widget=NumberInput) foreign_jobs_planned_daily_workers = forms.IntegerField(required=False, label=_("Daily/seasonal workers"), help_text=_("workers"), widget=NumberInput) foreign_jobs_current = YearBasedIntegerField(required=False, label=_("Current number of jobs for foreigners"), help_text=_("jobs")) foreign_jobs_current_employees = YearBasedIntegerField(required=False, label=_("Employees"), help_text=_("employees")) foreign_jobs_current_daily_workers = YearBasedIntegerField(required=False, label=_("Daily/seasonal workers"), help_text=_("workers")) tg_foreign_jobs_created_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) # Number of domestic jobs created tg_domestic_jobs_created = TitleField(required=False, label="", initial=_("Number of domestic jobs created")) domestic_jobs_created = forms.BooleanField(required=False, label=_("Number of domestic jobs created")) domestic_jobs_planned = forms.IntegerField(required=False, label=_("Planned number of domestic jobs"), help_text=_("jobs"), widget=NumberInput) domestic_jobs_planned_employees = forms.IntegerField(required=False, label=_("Employees"), help_text=_("employees"), widget=NumberInput) domestic_jobs_planned_daily_workers = forms.IntegerField(required=False, label=_("Daily/seasonal workers"), help_text=_("workers"), widget=NumberInput) domestic_jobs_current = YearBasedIntegerField(required=False, label=_("Current number of domestic jobs"), help_text=_("jobs")) domestic_jobs_current_employees = YearBasedIntegerField(required=False, label=_("Employees"), help_text=_("employees")) domestic_jobs_current_daily_workers = YearBasedIntegerField(required=False, label=_("Daily/seasonal workers"), help_text=_("workers")) tg_domestic_jobs_created_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) class Meta: name = 'employment'
class DealContractForm(BaseForm): form_title = _('Contracts') tg_contract = TitleField( required=False, label="", initial=_("Contract") ) contract_number = forms.IntegerField( required=False, label=_("Contract number") ) contract_date = forms.DateField( required=False, label=_("Contract date"), help_text="[dd:mm:yyyy]", input_formats=["%d.%m.%Y", "%d:%m:%Y", "%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y"] ) contract_expiration_date = forms.DateField( required=False, label=_("Contract expiration date"), help_text="[dd:mm:yyyy]", input_formats=["%d.%m.%Y", "%d:%m:%Y", "%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y"] ) sold_as_deal = forms.IntegerField( required=False, label=_("Sold as deal no.") ) tg_negotiation_status_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) # Duration of the agreement tg_agreement_duration = TitleField( required=False, label="", initial=_("Duration of the agreement") ) agreement_duration = YearBasedIntegerField( required=False, label=_("Duration of the agreement"), help_text=_("years") ) tg_agreement_duration_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) class Meta: name = 'spatial_data'
class AddDealOverallCommentForm(BaseForm): form_title = _('Overall Comment') # Coordinators and reviewers overall comments tg_overall = TitleField(required=False, label="", initial=_("Overall comment")) tg_overall_comment = forms.CharField(required=False, label="", widget=CommentInput) class Meta: name = 'overall_comment'
class DealGenderRelatedInfoForm(BaseForm): form_title = _('Gender-related info') tg_gender_specific_info = TitleField( required=False, label="", initial= _("Any gender-specific information about the investment and its impacts" )) tg_gender_specific_info_comment = forms.CharField(required=False, label="", widget=CommentInput) class Meta: name = 'gender-related_info'
class DealVGGTForm(BaseForm): form_title = _( 'Voluntary Guidelines on the Responsible Governance of Tenure (VGGT) / ' 'Principles for Responsible Agricultural Investments (PRAI)') tg_vggt = TitleField( required=False, initial=_( "Voluntary Guidelines on the Responsible Governance of Tenure (VGGT) / " "Principles for Responsible Agricultural Investments (PRAI)")) vggt_applied = forms.ChoiceField( required=False, label= _("Application of Voluntary Guidelines on the Responsible Governance of Tenure (VGGT)" ), choices=( (10, _("Yes")), (20, _("Partially")), (30, _("No")), ), widget=forms.RadioSelect) tg_vggt_applied_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) prai_applied = forms.ChoiceField( required=False, label= _("Application of Principles for Responsible Agricultural Investments (PRAI)" ), choices=( (10, _("Yes")), (20, _("Partially")), (30, _("No")), ), widget=forms.RadioSelect) tg_prai_applied_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) class Meta: name = 'vggt'
class AddInvestorForm(BaseForm): tg_general = TitleField(required=False, label="", initial=_("General")) investor_name = forms.CharField(required=False, label=_("Name"), max_length=255) country = forms.ChoiceField(required=False, label=_("Country"), choices=()) classification = forms.ChoiceField(required=False, label=_("Classification"), choices=Investor.classification_choices, widget=forms.RadioSelect) tg_general_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) def __init__(self, *args, **kwargs): if "instance" in kwargs: kwargs["initial"] = self.get_data(kwargs.pop("instance")) super(AddInvestorForm, self).__init__(*args, **kwargs) self.fields["country"].choices = [ ("", str(_("---------"))), (0, str(_("Multinational enterprise (MNE)"))) ] self.fields["country"].choices.extend([ (c.id, c.name) for c in Country.objects.all().order_by("name") ]) def save(self): return self def clean_investor(self): investor = int(self.cleaned_data["investor"] or 0) if investor and (investor not in [s.id for s in self.investor_choices]): raise forms.ValidationError("%s is no valid investor." % investor) return investor def get_attributes(self, request=None): taggroups = super(AddInvestorForm, self).get_attributes() return taggroups
class AddDealGeneralForm(BaseForm): form_title = _('General Info') # Land area tg_land_area = TitleField(required=False, label="", initial=_("Land area")) intended_size = forms.IntegerField(required=False, label=_("Intended size"), help_text=_("ha"), widget=NumberInput) contract_size = forms.IntegerField( required=False, label=_("Size under contract (leased or purchased area)"), help_text=_("ha"), widget=NumberInput) production_size = forms.IntegerField( required=False, label=_("Size in operation (production)"), help_text=_("ha"), widget=NumberInput) tg_land_area_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) # Intention of investment tg_intention = TitleField(required=False, label="", initial=_("Intention of investment")) intention = NestedMultipleChoiceField( required=False, label=_("Intention of the investment"), choices=intention_choices) tg_intention_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) # Nature of the deal tg_nature = TitleField(required=False, label="", initial=_("Nature of the deal")) nature = forms.MultipleChoiceField(required=False, label=_("Nature of the deal"), choices=nature_choices, widget=forms.CheckboxSelectMultiple) tg_nature_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) # Negotiation status, tg_negotiation_status = TitleField(required=False, label="", initial=_("Negotiation status")) negotiation_status = YearBasedChoiceField( required=False, label=_("Negotiation status"), choices=negotiation_status_choices) contract_number = forms.IntegerField(required=False, label=_("Contract number")) contract_date = forms.DateField(required=False, label=_("Contract date"), help_text="[dd:mm:yyyy]", input_formats=[ "%d.%m.%Y", "%d:%m:%Y", "%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y" ]) contract_expiration_date = forms.DateField( required=False, label=_("Contract expiration date"), help_text="[dd:mm:yyyy]", input_formats=[ "%d.%m.%Y", "%d:%m:%Y", "%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y" ]) sold_as_deal = forms.IntegerField(required=False, label=_("Sold as deal no.")) tg_negotiation_status_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput) # Duration of the agreement tg_agreement_duration = TitleField(required=False, label="", initial=_("Duration of the agreement")) agreement_duration = YearBasedIntegerField( required=False, label=_("Duration of the agreement"), help_text=_("years")) tg_agreement_duration_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput) # Implementation status tg_implementation_status = TitleField(required=False, label="", initial=_("Implementation status")) implementation_status = YearBasedChoiceField( required=False, label=_("Implementation status"), choices=implementation_status_choices) tg_implementation_status_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput) # Purchase price tg_purchase_price = TitleField(required=False, label="", initial=_("Purchase price")) purchase_price = forms.DecimalField(max_digits=19, decimal_places=2, required=False, label=_("Purchase price")) purchase_price_currency = forms.ModelChoiceField( required=False, label=_("Purchase price currency"), queryset=Currency.objects.all().order_by("ranking", "name")) purchase_price_type = forms.TypedChoiceField( required=False, label=_("Purchase price area type"), choices=price_type_choices, coerce=int) purchase_price_area = forms.IntegerField( required=False, label=_("Purchase price area"), help_text=_("ha"), widget=NumberInput(attrs={'class': 'test'})) tg_purchase_price_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) # Leasing fees tg_leasing_fees = TitleField(required=False, label="", initial=_("Leasing fees")) annual_leasing_fee = forms.DecimalField(max_digits=19, decimal_places=2, required=False, label=_("Annual leasing fee")) annual_leasing_fee_currency = forms.ModelChoiceField( required=False, label=_("Annual leasing fee currency"), queryset=Currency.objects.all().order_by("ranking", "name")) annual_leasing_fee_type = forms.TypedChoiceField( required=False, label=_("Annual leasing fee type"), choices=price_type_choices, coerce=int) annual_leasing_fee_area = forms.IntegerField( required=False, label=_("Purchase price area"), help_text=_("ha"), widget=NumberInput) tg_leasing_fees_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) # Contract farming tg_contract_farming = TitleField(required=False, label="", initial=_("Contract farming")) contract_farming = forms.ChoiceField(required=False, label=_("Contract farming"), choices=( (10, _("Yes")), (20, _("No")), ), widget=forms.RadioSelect) on_the_lease = forms.BooleanField(required=False, label=_("On leased / purchased area")) on_the_lease_area = YearBasedIntegerField( required=False, label=_("On leased / purchased area"), help_text=_("ha"), widget=NumberInput) on_the_lease_farmers = YearBasedIntegerField( required=False, label=_("On leased / purchased farmers"), help_text=_("farmers"), widget=NumberInput) on_the_lease_households = YearBasedIntegerField( required=False, label=_("On leased / purchased households"), help_text=_("households"), widget=NumberInput) off_the_lease = forms.BooleanField( required=False, label=_("Not on leased / purchased area (out-grower)")) off_the_lease_area = YearBasedIntegerField( required=False, label=_("Not on leased / purchased area (out-grower)"), help_text=_("ha"), widget=NumberInput) off_the_lease_farmers = YearBasedIntegerField( required=False, label=_("Not on leased / purchased farmers (out-grower)"), help_text=_("farmers"), widget=NumberInput) off_the_lease_households = YearBasedIntegerField( required=False, label=_("Not on leased / purchased households (out-grower)"), help_text=_("households"), widget=NumberInput) tg_contract_farming_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput) def clean_contract_date(self): date = self.cleaned_data["contract_date"] try: return date and date.strftime("%Y-%m-%d") or "" except: raise forms.ValidationError( _("Invalid date. Please enter a date in the format [dd:mm:yyyy]" )) class Meta: name = 'general_information'
class DealSecondaryInvestorForm(BaseForm): # Investor tg_investor = TitleField(required=False, label="", initial=_("Investor")) investor = forms.ChoiceField(required=False, label=_("Existing investor"), choices=()) #, widget=LivesearchSelect) investor_name = forms.CharField(required=False, label=_("Name"), max_length=255) country = forms.ChoiceField(required=False, label=_("Country"), choices=()) region = forms.ModelChoiceField( required=False, label=_("Region"), widget=forms.HiddenInput, queryset=Region.objects.all().order_by('name')) classification = forms.ChoiceField(required=False, label=_("Classification"), choices=Investor.classification_choices, widget=forms.RadioSelect) investment_ratio = forms.DecimalField(max_digits=19, decimal_places=2, required=False, label=_("Percentage of investment"), help_text=_("%")) tg_general_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) @print_execution_time_and_num_queries def __init__(self, *args, **kwargs): super(DealSecondaryInvestorForm, self).__init__(*args, **kwargs) investor = kwargs.pop("investor", None) self.fields["investor"].initial = investor self._fill_investor_choices() self._fill_country_choices() def clean_investor(self): investor = int(self.cleaned_data["investor"] or 0) if investor and (investor not in [s[0] for s in self.investor_choices]): raise forms.ValidationError("%s is no valid investor." % investor) return investor def clean(self): cleaned_data = super(DealSecondaryInvestorForm, self).clean() investor = cleaned_data.get("investor", None) investor_name = cleaned_data.get("investor_name", None) if not investor and not investor_name: raise forms.ValidationError( "Please select an investor or investor name.") return cleaned_data def has_investor(self): if self.initial.get("investor"): return True elif self.is_valid() and self.cleaned_data.get("investor"): return True return False @print_execution_time_and_num_queries def _fill_investor_choices(self): self.investor_choices = [(investor.id, self._investor_description(investor)) for investor in Investor.objects.filter( fk_status_id__in=(2, 3)).order_by('name')] self.fields["investor"].choices = list( self.fields["investor"].choices)[:1] self.fields["investor"].choices.extend(self.investor_choices) def _investor_description(self, investor): return investor.name + ' (' + self._investor_country_name( investor) + ')' + ' ' + self._investor_classification(investor) def _investor_country_name(self, investor): return Country.objects.get( pk=investor.fk_country_id).name if investor.fk_country_id else '-' def _investor_classification(self, investor): return investor.get_classification_display( ) if investor.classification else '-' @print_execution_time_and_num_queries def _fill_country_choices(self): self.fields["country"].choices = [ ("", str(_("---------"))), (0, str(_("Multinational enterprise (MNE)"))) ] self.fields["country"].choices.extend([ (c.id, c.name) for c in Country.objects.all().order_by("name") ])
class DealProduceInfoForm(BaseForm): form_title = _('Produce info') # Detailed crop, animal and mineral information tg_crop_animal_mineral = TitleField( required=False, label="", initial=_("Detailed crop, animal and mineral information")) crops = forms.ModelMultipleChoiceField(required=False, label=_("Crops"), queryset=Crop.objects.all()) crops_other = forms.CharField(required=False, label=_("Other crops")) tg_crops_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) animals = forms.ModelMultipleChoiceField(required=False, label=_("Livestock"), queryset=Animal.objects.all()) animals_other = forms.CharField(required=False, label=_("Other livestock")) tg_animals_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) minerals = forms.ModelMultipleChoiceField(required=False, label=_("Resources"), queryset=Mineral.objects.all()) minerals_other = forms.CharField(required=False, label=_("Other resources")) tg_minerals_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) contract_farming_crops = forms.ModelMultipleChoiceField( required=False, label=_("Contract farming crops"), queryset=Crop.objects.all()) contract_farming_crops_other = forms.CharField( required=False, label=_("Other contract farming crops")) # Detailed contract farming crop, animal and mineral information tg_contract_farming_crop_animal_mineral = TitleField( required=False, initial=_( "Detailed contract farming crop, animal and mineral information")) tg_contract_farming_crops_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput) contract_farming_animals = forms.ModelMultipleChoiceField( required=False, label=_("Contract farming livestock"), queryset=Animal.objects.all()) contract_farming_animals_other = forms.CharField( required=False, label=_("Other contract farming livestock")) tg_contract_farming_animals_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput) # Use of produce tg_use_of_produce = TitleField(required=False, label="", initial=_("Use of produce")) has_domestic_use = forms.BooleanField(required=False, label=_("Has domestic use")) domestic_use = forms.IntegerField(required=False, label=_("Domestic use"), help_text=_("%"), widget=NumberInput) has_export = forms.BooleanField(required=False, label=_("Has export")) export = forms.IntegerField(required=False, label=_("Export"), help_text=_("%"), widget=NumberInput) export_country1 = forms.ModelChoiceField( required=False, label=_("Country 1"), queryset=Country.objects.all().order_by("name")) export_country1_ratio = forms.IntegerField(required=False, label=_("Country 1 ratio"), help_text=_("%"), widget=NumberInput) export_country2 = forms.ModelChoiceField( required=False, label=_("Country 2"), queryset=Country.objects.all().order_by("name")) export_country2_ratio = forms.IntegerField(required=False, label=_("Country 2 ratio"), help_text=_("%"), widget=NumberInput) export_country3 = forms.ModelChoiceField( required=False, label=_("Country 3"), queryset=Country.objects.all().order_by("name")) export_country3_ratio = forms.IntegerField(required=False, label=_("Country 3 ratio"), help_text=_("%"), widget=NumberInput) tg_use_of_produce_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) # In-country processing of produce tg_in_country_processing = TitleField( required=False, label="", initial=_("In country processing of produce")) in_country_processing = forms.ChoiceField( required=False, label=_("In country processing of produce"), choices=( (10, _("Yes")), (20, _("No")), ), widget=forms.RadioSelect) tg_in_country_processing_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput) processing_facilities = forms.CharField( required=False, label=_( "Processing facilities / production infrastructure of the project (e.g. oil mill, " "ethanol distillery, biomass power plant etc.)"), widget=CommentInput) in_country_end_products = forms.CharField( required=False, label=_("In-country end products of the project"), widget=CommentInput) class Meta: name = 'produce_info'
class DealLocalCommunitiesForm(BaseForm): form_title = _('Local communities / indigenous peoples') # Names of affected communities and indigenous peoples tg_names_of_affected = TitleField( required=False, label="", initial=_("Names of communities / indigenous peoples affected") ) name_of_community = forms.CharField( required=False, label=_("Name of community"), widget=forms.TextInput ) name_of_indigenous_people = forms.CharField( required=False, label=_("Name of indigenous people"), widget=forms.TextInput ) tg_affected_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) # Recognitions status of community land tenure tg_recognition_status = TitleField( required=False, label="", initial=_("Recognitions status of community land tenure") ) recognition_status = forms.MultipleChoiceField( required=False, label=_("Recognition status of community land tenure"), choices=( (10, _("Community land formally recognized by law or decree")), (20, _("Community land not formally recognized")), (30, _("Indigenous land formally recognized by law or decree")), (40, _("Indigenous land not formally recognized")), ), widget=forms.CheckboxSelectMultiple ) tg_recognition_status_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) # Consultation of local community tg_community_consultation = TitleField( required=False, label="", initial=_("Consultation of local community") ) community_consultation = forms.ChoiceField( required=False, label=_("Community consultation"), choices=( (10, _("Not consulted")), (20, _("Limited consultation")), (30, _("Free, Prior and Informed Consent (FPIC)")), (40, _("Certified Free, Prior and Informed Consent (FPIC)")), (50, _("Other")), ), widget=forms.RadioSelect ) tg_community_consultation_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) # How did community react? tg_community_reaction = TitleField( required=False, label="", initial=_("How did community react?") ) community_reaction = forms.ChoiceField( required=False, label=_("Community reaction"), choices=( (10, _("Consent")), (20, _("Mixed reaction")), (30, _("Rejection")), ), widget=forms.RadioSelect ) tg_community_reaction_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) # Land conflicts tg_land_conflicts = TitleField( required=False, label="", initial=_("Presence of land conflicts") ) land_conflicts = forms.ChoiceField( required=False, label=_("Presence of land conflicts"), choices=( (10, _("Yes")), (20, _("No")), ), widget=forms.RadioSelect ) tg_land_conflicts_comment = forms.CharField( required=False, label=_("Please specify details in Additional comments"), widget=CommentInput ) # Displacement of people tg_displacement_of_people = TitleField( required=False, label="", initial=_("Displacement of people") ) displacement_of_people = forms.ChoiceField( required=False, label=_("Displacement of people"), choices=( (10, _("Yes")), (20, _("No")), ), widget=forms.RadioSelect ) number_of_displaced_people = forms.IntegerField( required=False, label=_("Number of people actually displaced"), widget=NumberInput ) number_of_displaced_households = forms.IntegerField( required=False, label=_("Number of households actually displaced"), widget=NumberInput ) number_of_people_displaced_from_community_land = forms.IntegerField( required=False, label=_("Number of people displaced out of their community land"), widget=NumberInput ) number_of_people_displaced_within_community_land = forms.IntegerField( required=False, label=_("Number of people displaced staying on community land"), widget=NumberInput ) number_of_people_displaced_from_fields = forms.IntegerField( required=False, label=_('Number of people displaced "only" from their agricultural fields'), widget=NumberInput ) number_of_people_displaced_on_completion = forms.IntegerField( required=False, label=_('Number of people facing displacement once project is fully implemented'), widget=NumberInput ) tg_number_of_displaced_people_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) tg_negative_impacts = TitleField( required=False, label="", initial=_("Negative impacts for local communities") ) negative_impacts = forms.MultipleChoiceField( required=False, label=_("Negative impacts for local communities"), choices=( (10, _("Environmental degradation")), (20, _("Socio-economic")), (30, _("Cultural loss")), (40, _("Eviction")), (50, _("Displacement")), (60, _("Violence")), (70, _("Other")), ), widget=forms.CheckboxSelectMultiple ) tg_negative_impacts_comment = forms.CharField( required=False, label=_("Please specify details in additional comments"), widget=CommentInput ) # Promised compensation tg_promised_compensation = TitleField( required=False, label="", initial=_("Promised or received compensation") ) promised_compensation = forms.CharField( required=False, label=_("Promised compensation (e.g. for damages or resettlements)"), widget=CommentInput ) received_compensation = forms.CharField( required=False, label=_("Received compensation (e.g. for damages or resettlements)"), widget=CommentInput ) # Promised benefits for local communities tg_promised_benefits = TitleField( required=False, label="", initial=_("Promised benefits for local communities") ) promised_benefits = forms.MultipleChoiceField( required=False, label=_("Promised benefits for local communities"), choices=( (10, _("Health")), (20, _("Education")), (30, _("Productive infrastructure (e.g. irrigation, tractors, machinery...)")), (40, _("Roads")), (50, _("Capacity Building")), (60, _("Financial Support")), (70, _("Community shares in the investment project")), (80, _("Other")), ), widget=forms.CheckboxSelectMultiple ) tg_promised_benefits_comment = forms.CharField( required=False, label=_("Please specify in additional comments"), widget=CommentInput ) # Materialized benefits for local communities tg_materialized_benefits = TitleField( required=False, label="", initial=_("Materialized benefits for local communities") ) materialized_benefits = forms.MultipleChoiceField( required=False, label=_("Materialized benefits for local communities"), choices=( (10, _("Health")), (20, _("Education")), (30, _("Productive infrastructure (e.g. irrigation, tractors, machinery...)")), (40, _("Roads")), (50, _("Capacity Building")), (60, _("Financial Support")), (70, _("Community shares in the investment project")), (80, _("Other")), ), widget=forms.CheckboxSelectMultiple ) tg_materialized_benefits_comment = forms.CharField( required=False, label=_("Please specify in additional comments"), widget=CommentInput ) # Presence of organizations and actions taken (e.g. farmer organizations, NGOs, etc.) tg_presence_of_organizations = TitleField( required=False, initial=_( "Presence of organizations and actions taken (e.g. farmer organizations, NGOs, etc.)" ) ) presence_of_organizations = forms.CharField( required=False, label=_( "Presence of organizations and actions taken (e.g. farmer organizations, NGOs, etc.)" ), widget=CommentInput ) class Meta: name = 'local_communities'
class DealDataSourceForm(BaseForm): DEBUG = False tg_data_source = TitleField(required=False, label="", initial=_("Data source")) type = forms.TypedChoiceField( required=False, label=_("Data source type"), choices=( (10, _("Media report")), (20, _("Research Paper / Policy Report")), (30, _("Government sources")), (40, _("Company sources")), (50, _("Contract")), (60, _("Contract (contract farming agreement)")), (70, _("Personal information")), (80, _("Crowdsourcing")), (90, _("Other (Please specify in comment field)")), ), coerce=int) url = forms.URLField( required=False, label=_("New URL"), help_text=_( "PDF will be generated automatically, leave empty for file upload") ) file = FileFieldWithInitial(required=False, label=_("New file")) pdf_not_public = forms.BooleanField(required=False, label=_("Keep PDF not public")) publication_title = forms.CharField(required=False, label=_("Publication title")) date = forms.DateField(required=False, label=_("Date"), help_text="[dd:mm:yyyy]", input_formats=[ "%d.%m.%Y", "%d:%m:%Y", "%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y" ]) # Optional personal information for Crowdsourcing and Personal information name = forms.CharField(required=False, label=_("Name")) company = forms.CharField(required=False, label=_("Organisation")) email = forms.CharField(required=False, label=_("Email")) phone = forms.CharField(required=False, label=_("Phone")) includes_in_country_verified_information = forms.BooleanField( required=False, label=_("Includes in-country-verified information")) open_land_contracts_id = forms.CharField(required=False, label=_("OpenLandContracts ID")) tg_data_source_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) def clean_date(self): date = self.cleaned_data["date"] try: return date and date.strftime("%Y-%m-%d") or "" except: raise forms.ValidationError( _("Invalid date. Please enter a date in the format [dd:mm:yyyy]" )) def clean_file(self): file = self.cleaned_data["file"] if file and isinstance(file, File): n = file.name.split(".") # cleanup special charachters in filename file.name = "%s.%s" % (slugify(n[0]), n[1]) if len(n) > 1 else slugify(n[0]) return file def get_availability_total(self): return 4 @classmethod def get_data(cls, deal, taggroup, next_taggroup): from django.db.models import Q belongs_to_data_source = Q(attributes__contains=['file']) | \ Q(attributes__contains=['url']) | \ Q(attributes__contains=['type']) | \ Q(name__icontains='data_source') next_taggroup_id = next_taggroup.id if next_taggroup else ActivityAttributeGroup.objects.order_by( 'pk').last().id if hasattr(deal.activity, 'history_date'): # isinstance(deal, DealHistoryItem): deal_date = deal.activity.history_date deal_activity = Activity.objects.get( pk=deal.activity.id).history.as_of(deal_date) else: deal_activity = deal.activity tags = ActivityAttributeGroup.objects.filter(fk_activity=deal_activity).\ filter(pk__gte=taggroup.id).filter(pk__lte=next_taggroup_id).\ filter(belongs_to_data_source).values_list('attributes', flat=True) attributes = {} for tag in tags: for key in tag.keys(): if key in attributes and attributes[key] != tag[key]: # raise RuntimeError() # print( # 'ALERT: found different values under the same tag group. Deal ID {}, taggroup {}, tags {}'.format( # deal.activity.activity_identifier, taggroup.id, str(tags) # )) pass attributes[key] = tag[key] return attributes
class ChangeDealActionCommentForm(AddDealActionCommentForm): tg_action = TitleField(required=False, label="", initial=_("Action comment")) tg_action_comment = forms.CharField(required=True, label="", widget=CommentInput)
class DealWaterForm(BaseForm): form_title = _('Water') tg_water_extraction_envisaged = TitleField( required=False, initial=_("Water extraction envisaged") ) water_extraction_envisaged = forms.ChoiceField( required=False, label=_("Water extraction envisaged"), choices=( (10, _("Yes")), (20, _("No")), ), widget=forms.RadioSelect ) tg_water_extraction_envisaged_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) tg_source_of_water_extraction = TitleField( required=False, initial=_("Source of water extraction") ) source_of_water_extraction = NestedMultipleChoiceField( required=False, label=_("Source of water extraction"), choices=( (10, _("Groundwater"), None), (20, _("Surface water"), ( (21, _("River")), (22, _("Lake")), )), ) ) tg_source_of_water_extraction_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) tg_how_much_do_investors_pay = TitleField( required=False, initial=_("How much do investors pay for water and the use of water infrastructure?") ) tg_how_much_do_investors_pay_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) tg_water_extraction_amount = TitleField( required=False, initial=_("How much water is extracted?") ) water_extraction_amount = forms.IntegerField( required=False, label=_("Water extraction amount"), help_text=mark_safe(_("m³/year")), widget=NumberInput ) tg_water_extraction_amount_comment = forms.CharField( required=False, label=_("Additional comments"), widget=CommentInput ) use_of_irrigation_infrastructure = forms.ChoiceField( required=False, label=_("Use of irrigation infrastructure"), choices=( (10, _("Yes")), (20, _("No")), ), widget=forms.RadioSelect ) tg_use_of_irrigation_infrastructure_comment = forms.CharField( required=False, label=_("Please specify in additional comments"), widget=CommentInput ) water_footprint = forms.CharField( required=False, label=_("Water footprint of the investment project"), widget=CommentInput ) class Meta: name = 'water'
class DealPrimaryInvestorForm(BaseForm): tg_primary_investor = TitleField(required=False, label="", initial=_("Primary investor")) project_name = forms.CharField(required=False, label=_("Name of the investment project"), max_length=255) # TODO fix #primary_investor = forms.ChoiceField(required=False, label=_("Existing primary investor"), choices=PrimaryInvestor.objects._get_all_active_primary_investors_choices(), widget=PrimaryInvestorSelect) primary_investor = PrimaryInvestorField( required=False, label=_("Existing primary investor")) tg_primary_investor_comment = forms.CharField( required=False, label=_("Additional comments regarding investors"), widget=CommentInput) def __init__(self, *args, **kwargs): super(DealPrimaryInvestorForm, self).__init__(*args, **kwargs) self.fields["primary_investor"].choices = [ ("", str(_("---------"))), ] + self.fields["primary_investor"].get_choices() def get_primary_investor(self): primary_investor = {"op": "add"} for j, taggroup in enumerate( super(DealPrimaryInvestorForm, self).get_attributes()): # Existing primary investor? for t in taggroup["tags"]: if t["key"] == "primary_investor" and t["value"]: primary_investor["op"] = "select" primary_investor["id"] = t["value"] if t["key"] == "primary_investor_name": primary_investor["name"] = t["value"] return primary_investor def get_attributes(self, request=None): taggroups = super(DealPrimaryInvestorForm, self).get_attributes() for tg in taggroups: tags = [] for t in tg["tags"]: if t["key"] == "project_name": tags.append(t) tg["tags"] = tags return taggroups @classmethod def get_data(cls, activity): data = super(DealPrimaryInvestorForm, cls).get_data(activity) primary_investor = PrimaryInvestor.objects.get_primary_investor_for_activity( activity) if primary_investor: data[ "primary_investor"] = primary_investor.primary_investor_identifier return data def get_availability(self): """ Availability of investor form is 1 if a primary investor is defined """ if self.data.get("primary_investor", None) or self.data.get( "primary_investor_name", None): return 1 return 0 def get_availability_total(self): return 1 def clean_primary_investor(self): pi_id = None if self.data.get("primary_investor"): pi_id = int(self.data.get("primary_investor", 0)) choices = dict(self.fields["primary_investor"].choices).keys() if pi_id and pi_id not in choices: #self.fields["primary_investor"].choices.append([pi_id, pi_name]) #c_old = self.fields["primary_investor"].choices #self.base_fields["primary_investor"].choices.append([pi_id, pi_name]) choices = self.fields["primary_investor"].get_choices() self.fields["primary_investor"].choices = choices self.base_fields["primary_investor"].choices = choices #self.base_fields["primary_investor"].update_choices() #c_new = self.fields["primary_investor"].choices return self.cleaned_data
class AddDealActionCommentForm(BaseForm): form_title = _('Action Comment') tg_action = TitleField(required=False, label="", initial=_("Action comment")) tg_action_comment = forms.CharField(required=False, label="", widget=CommentInput) fully_updated = forms.BooleanField(required=False, label=_("Fully updated")) fully_updated_history = forms.CharField( required=False, label=_("Fully updated history"), widget=forms.Textarea(attrs={ "readonly": True, "cols": 80, "rows": 5 })) tg_not_public = TitleField(required=False, label="", initial=_("Public deal")) not_public = forms.BooleanField( required=False, label=_("Not public"), help_text=_("Please specify in additional comment field")) not_public_reason = forms.ChoiceField( required=False, label=_("Reason"), choices=( (0, _("---------")), (10, _("Temporary removal from PI after criticism")), (20, _("Research in progress")), )) tg_not_public_comment = forms.CharField(required=False, label=_("Additional comments"), widget=CommentInput) tg_feedback = TitleField(required=False, label="", initial=_("Feedback")) assign_to_user = UserModelChoiceField( required=False, label=_("Assign to"), queryset=User.objects.filter( groups__name__in=("Research admins", "Research assistants")).order_by("username"), empty_label=_("Unassigned")) tg_feedback_comment = forms.CharField(required=False, label=_("Feedback comment"), widget=CommentInput) def get_action_comment(self): for j, taggroup in enumerate( super(AddDealActionCommentForm, self).get_attributes()): if taggroup["main_tag"]["value"] == "action": return taggroup["comment"] return "" def get_feedback(self): for j, taggroup in enumerate( super(AddDealActionCommentForm, self).get_attributes()): if taggroup["main_tag"]["value"] == "feedback": tags = taggroup.get("tags", []) if len(tags) > 0: feedback = { "assigned_to": tags[0].get("value"), "comment": taggroup.get("comment") } return feedback return "" def get_fully_updated(self): for j, taggroup in enumerate( super(AddDealActionCommentForm, self).get_attributes()): if taggroup["main_tag"]["value"] == "action": for tag in taggroup.get("tags", []): if tag.get("key") == "fully_updated": return tag.get("value") return False #def get_attributes(self, request=None): # taggroups = [] # for tg in super(AddDealActionCommentForm, self).get_attributes(): # if tg["main_tag"]["value"] in ("action", "feedback"): # continue # else: # taggroups.append(tg) # return taggroups @classmethod def get_data(cls, activity): from inspect import currentframe, getframeinfo data = super(AddDealActionCommentForm, cls).get_data(activity) if False: a_feedback = A_Feedback.objects.filter(fk_activity=activity) else: frameinfo = getframeinfo(currentframe()) print('*** feedback not yet implemented! ', frameinfo.filename, frameinfo.lineno) a_feedback = [] if len(a_feedback) > 0: feedback = a_feedback[0] data.update({ "assign_to_user": feedback.fk_user_assigned.id, "tg_feedback_comment": feedback.comment, }) if False: fully_updated_history = Activity.objects.get_fully_updated_history( activity.activity_identifier) else: frameinfo = getframeinfo(currentframe()) print('*** fully updated history not yet implemented! ', frameinfo.filename, frameinfo.lineno) fully_updated_history = [] fully_updated = [] for h in fully_updated_history: fully_updated.append("%s - %s: %s" % (DateFormat( h.fully_updated).format("Y-m-d H:i:s"), h.username, h.comment)) data.update({"fully_updated_history": "\n".join(fully_updated)}) return data class Meta: name = 'action_comment'