Line 1:
Line 1:
+
<!-- BEGIN origin interlang links -->
+
<!-- You can edit this section but do NOT remove these comments
+
Links below will be automatically replicated on translated pages by PolyglotBot -->
+
[[fr:Module_CustomFields_Cases_FR]]
+
<!-- END interlang links -->
+
[[Category:CustomFields]]
[[Category:CustomFields]]
{{TemplateDocDevEn}}
{{TemplateDocDevEn}}
Line 152:
Line 158:
* static condition: choices are restrained on a condition that never changes (eg: only show third-parties that are suppliers, or lowercase all data on sql insertion, or check that a field is above a certain number, etc.).
* static condition: choices are restrained on a condition that never changes (eg: only show third-parties that are suppliers, or lowercase all data on sql insertion, or check that a field is above a certain number, etc.).
−
* semi-dynamic condition: choices that are constrained on a static table but based on the value of another field/customfield.
+
* semi-dynamic condition: choices that are constrained on a static table but based on the value of another field/customfield. This is also commonly called "Cascaded dropdown lists" or "Dynamically linked dropdown lists".
* dynamic: everything is dynamic: choices are based on a subfield of a field of the current module, so that there's no material table and it's impossible to create a view (because you would need to create one view per id) (eg: show only the contacts attached to the third-party being accessed)
* dynamic: everything is dynamic: choices are based on a subfield of a field of the current module, so that there's no material table and it's impossible to create a view (because you would need to create one view per id) (eg: show only the contacts attached to the third-party being accessed)
* timed condition: a condition that is based on time or recurrence (eg: at 5:00 AM delete old records, etc..)
* timed condition: a condition that is based on time or recurrence (eg: at 5:00 AM delete old records, etc..)
Line 164:
Line 170:
=== Static condition ===
=== Static condition ===
+
* Constraint WHERE clause (when creating/editing a custom field, you can specify your own WHERE conditions).
* View: create a view on the table based on the condition, and then create a custom field constrained on this view (which is just like any table), eg: only show third-parties that are suppliers:
* View: create a view on the table based on the condition, and then create a custom field constrained on this view (which is just like any table), eg: only show third-parties that are suppliers:
<source lang="php">
<source lang="php">
Line 179:
Line 186:
=== Semi-dynamic condition ===
=== Semi-dynamic condition ===
+
* CustomFields's Cascade option is ideal in most cases, and if not enough, you can use the Cascade Custom option and Overloading Functions.
* View
* View
* Check
* Check
* Trigger
* Trigger
−
* CustomFields's overload functions
=== Dynamic condition ===
=== Dynamic condition ===
−
* CustomFields's overload functions
+
* CustomFields's Cascade Custom and Overload functions
+
* Recursive Remote Fields Access
* Making your own module, which calls the CustomFields class
* Making your own module, which calls the CustomFields class
Line 194:
Line 202:
* Cron job
* Cron job
* CustomFields's overload functions
* CustomFields's overload functions
+
+
= Cascading =
+
+
A simple example of [http://wiki.dolibarr.org/index.php/Module_CustomFields#Cascade cascading to select a location] can be found in the user manual.
+
+
But you can do a lot more with cascading if you combine it with other options, such as Duplication and Hide. Here is an example:
+
+
Let's say that in invoices, you want to be able to select a contact of the society selected for this invoice. Of course, you want that the list of contacts show only the contacts related to the society (ie: that you added on the Third-Party datasheet of this society).
+
+
To do that, you have to proceed in two steps:
+
+
1- Create a custom field "soccpy_nom" constrained on llx_society that will duplicate the society's id. This is necessary because other custom fields can only be cascaded using other custom fields, not any Dolibarr fields. Using duplication allows you to duplicate any Dolibarr field (and even $_GET and $_POST), so that you can use them to cascade. Copy the parameters as shown in this image:
+
+
[[File:Cf-case-cascade-contacts1.png]]
+
+
2- Create a custom field "contact_firstname_lastname" with Cascade option with parent "soccpy_nom" and constrained on the table llx_socpeople (the table of the contacts), which will show the list of contacts associated only to the selected society in soccpy_nom. Copy the parameters as shown in this image:
+
+
[[File:Cf-case-cascade-contacts2.png]]
+
+
And voila, you're done! The field soccpy_nom should be hidden so you won't see it, but you should see the field contact_firstname_lastname and you can check that only the contacts related to the society selected for the current invoice are shown.
= Overloading functions =
= Overloading functions =
Line 202:
Line 230:
The goal is to show two custom fields on the Third-Party module: one which gives the zone (secteur) of the third-party (Isere, Alpes du sud, Haute-Savoie...) and the other which gives relative to the zone the list of all the ski resorts (station_a) inside the selected zone.
The goal is to show two custom fields on the Third-Party module: one which gives the zone (secteur) of the third-party (Isere, Alpes du sud, Haute-Savoie...) and the other which gives relative to the zone the list of all the ski resorts (station_a) inside the selected zone.
+
+
NOTE: this will show how to manually manage this kind of requirements using [[Module_CustomFields#Overloading_functions:_Adding_your_own_management_code_for_custom_fields|overloading functions]], but in latest CustomFields releases, the same solution can be achieved automatically using the [[Module_CustomFields#Cascade|Cascade option]].
We have one table '''llx_k_station''' (rowid, station (char50), secteur(char50)) which contains the following:
We have one table '''llx_k_station''' (rowid, station (char50), secteur(char50)) which contains the following:
Line 328:
Line 358:
// Crafting a dummy intervention object
// Crafting a dummy intervention object
−
$fromobject = object(); // Init the object
+
$fromobject = new stdClass(); // Init an empty object
$fromobject->id = $sourceid; // We need the id and..
$fromobject->id = $sourceid; // We need the id and..
$fromobject->table_element = 'fichinter'; // the table_element (name of the table)
$fromobject->table_element = 'fichinter'; // the table_element (name of the table)
Line 343:
Line 373:
Thank's to netassopro for the tip.
Thank's to netassopro for the tip.
−
= Modify the total price of every product/service line with a coefficient (without tampering the discount) =
+
= Modify the total global price with a coefficient (without tampering the discount) =
+
+
This is more troublesome than modifying the total price per product/service line, because the total global price of an object (let's say an invoice, but this also works for any other object) is always recomputed by summing the prices and quantity of each product/service line. This means that although there's an entry "total_ttc" in the database to store the invoice's total price, this price is in fact always recomputed, it's never used as-is. Thus, it's useless to change only the database record: we need to inject some code to change how the total price is computed.
+
+
This could be done using an overloading function or a trigger, but unluckily, Dolibarr doesn't call a trigger nor a hook when recomputing the price. We thus need to edit core files to do what we want.
+
+
However, the bright side is that we can cleverly edit just two functions from one core file: update_price() and getMarginInfos() from /htdocs/core/class/commonobject.class.php , and everything should run smoothly. Beware that if you update Dolibarr, you will need to redo these two modifications in the code.
+
+
First, you need to create a new custom field called "global_coefficient" in Invoices (not Invoices Lines!). Then you can continue to the subchapters below.
+
+
Also note that this global coefficient is also compatible with per line coefficients (as described in the next chapter), thus you can use a global coefficient and per line coefficients at the same time. You can also use multiple global coefficient if you wish.
+
+
Another note: if you have a grid of discounts depending on quantity or price or whatever parameter, you can program a precomputation code using a Custom Ajax function (this way, your discounts will be automatically computed, but then you can still manually enter them for particular cases since the custom field is editable).
+
+
== Implement the change of global price in most of Dolibarr (including remaining debt to pay and PDF and ODT) ==
+
+
The change we will implement here will reflect the new total price with the global coefficient in most of Dolibarr's code, since we will here change the main function that is usually called to update and get the total price.
+
+
Open /htdocs/core/class/commonobject.class.php and look for the function update_price().
+
+
You should see the following:
+
+
<source lang="php">
+
function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller='')
+
{
+
global $conf;
+
+
include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
+
</source>
+
+
Just below the include_once line, add the following:
+
+
<source lang="php">
+
// Global coefficient (CustomFields)
+
include_once DOL_DOCUMENT_ROOT.'/customfields/class/customfields.class.php';
+
include_once DOL_DOCUMENT_ROOT.'/customfields/conf/conf_customfields_func.lib.php';
+
$customfields = new CustomFields($this->db, $this->table_element);
+
// Get object's id (either stored in property "id" or "rowid")
+
$this_id = (!empty($this->id)) ? $this->id : $this->rowid;
+
// Load custom fields records
+
$cf_parent_record = $customfields->fetch($this_id);
+
</source>
+
+
This will load the global_coefficient custom field (and also any other custom field you have defined for invoices).
+
+
Now scroll below, and you should see this:
+
+
<source lang="php">
+
while ($i < $num)
+
{
+
$obj = $this->db->fetch_object($resql);
+
+
... (lots of code)
+
+
i++;
+
}
+
+
// Add revenue stamp to total
+
$this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0;
+
+
$this->db->free($resql);
+
</source>
+
+
This is the end of the loop that is summing each product/service line price to compute the total price. Just after this loop, you should see this:
+
+
<source lang="php">
+
// Now update global field total_ht, total_ttc and tva
+
$fieldht='total_ht';
+
$fieldtva='tva';
+
$fieldlocaltax1='localtax1';
+
$fieldlocaltax2='localtax2';
+
$fieldttc='total_ttc';
+
// Specific code for backward compatibility with old field names
+
if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total';
+
if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
+
if ($this->element == 'propal') $fieldttc='total';
+
</source>
+
+
Between those two blocks of code (so just above // Now update global field total_ht, total_ttc and tva), you can place the following:
+
+
<source lang="php">
+
// Global coefficient (CustomFields)
+
if (!empty($cf_parent_record->global_coefficient)) { // avoid applying the coefficient if empty (this will return a 0 price)
+
$this->total_ht = $this->total_ht * $cf_parent_record->global_coefficient;
+
$this->total_tva = $this->total_tva * $cf_parent_record->global_coefficient;
+
$this->total_ttc = $this->total_ttc * $cf_parent_record->global_coefficient;
+
}
+
</source>
+
+
Done, now try to add/edit a product/service line, and the total price should be affected by the global coefficient.
+
+
Note that this modification '''needs only to be done once for all modules''', you then just have to create a custom field named "global_coefficient" in every module you want to apply this coefficient.
+
+
== Implementing the change of price in margin module ==
+
+
If you enabled the margin module, you should see that the coefficient is not applied there, but it's easy to fix that.
+
+
Open the file /htdocs/core/class/commonobject.class.php and find the function getMarginInfos(), then inside find the following lines:
+
+
<source lang="php">
+
foreach($this->lines as $line) {
+
if (empty($line->pa_ht) && isset($line->fk_fournprice) && !$force_price) {
+
$product = new ProductFournisseur($this->db);
+
if ($product->fetch_product_fournisseur_price($line->fk_fournprice))
+
$line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
+
if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == "2" && $product->fourn_unitcharges > 0)
+
$line->pa_ht += $product->fourn_unitcharges;
+
}
+
// si prix d'achat non renseigné et devrait l'être, alors prix achat = prix vente
+
if ((!isset($line->pa_ht) || $line->pa_ht == 0) && $line->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) {
+
$line->pa_ht = $line->subprice * (1 - ($line->remise_percent / 100));
+
}
+
</source>
+
+
This is where the lines are filled with margin infos. The price has just been fetched here, and we will now modify it with the coefficient before the price gets used for margin computation.
+
+
To optimize things up, we will load the custom fields before the loop (because they don't change between product/service lines, they are the custom fields of the parent object), and then apply the global_coefficient inside the loop.
+
+
Just above the code we found (just before the for loop), paste the following:
+
+
<source lang="php">
+
// Global coefficient (CustomFields)
+
dol_include_once('/customfields/lib/customfields_aux.lib.php');
+
// Get object's id (either stored in property "id" or "rowid")
+
$this_id = (!empty($this->id)) ? $this->id : $this->rowid;
+
// Load custom fields records
+
$customfields = customfields_fill_object($this);
+
</source>
+
+
And now, just below the code we found, inside the loop (and just above the comment: "// calcul des marges"), paste the following:
+
+
<source lang="php">
+
// Global coefficient (CustomFields)
+
// Apply the coefficient
+
if (!empty($this->customfields->cf_global_coefficient)) {
+
$line->pa_ht = $line->pa_ht * $this->customfields->cf_global_coefficient;
+
$line->subprice = $line->subprice * $this->customfields->cf_global_coefficient;
+
}
+
</source>
+
+
Note that here we cheated a bit: we do not compute the coefficient on the global total price, but rather per product/service line price. This is done on purpose, because mathematically this should produce no difference, and it also allows Dolibarr to continue peacefully with its margin calculations (else we would have to adapt all those computations, which would imply a lot more of code changes!).
+
+
That's all, the price should be reflected in the margin. Just refresh the page to reflect the change.
+
+
Note that this modification '''needs only to be done once for all modules''', you then just have to create a custom field named "global_coefficient" in every module you want to apply this coefficient.
+
+
== Refresh the price instantly ==
+
+
Maybe you noticed one glitch: when you modify the global_coefficient, the global total price isn't updated until you add/edit a product/service line. This is because the update_price() function is only called when we add/edit a product/service line.
+
+
To fix that, we need now to force the refreshing of price. To do that, we will use an "aftersave" overloading function, which will execute commands after our custom field is saved.
+
+
Go to the folder /htdocs/customfields/fields and rename the file customfields_fields_extend.lib.php.example into customfields_fields_extend.lib.php .
+
+
Now, open it in your favourite text editor, and add the following function :
+
+
<source lang="php">
+
function customfields_field_aftersave_facture_global_coefficient (&$currentmodule, &$object, &$action, &$user, &$customfields, &$field, &$name, &$value, $fields) {
+
// Force refreshing total price
+
$object->update_price(0, 'auto');
+
}
+
</source>
+
+
That's all. Now, when you edit your global_coefficient, this will force refresh the total price.
+
+
However, you will still notice one last glitch: when you edit the global_coefficient, the total price isn't reflected instantly, you must refresh the webpage once to see the new price. This is because of how the datasheet and the CustomFields hook are designed: CustomFields is called only exactly where the custom fields are place, thus it is called after the total price, the margin and the remaining debt are printed. Thus, CustomFields updates the value of your custom field only after all those informations get printed, and thus it cannot modify them at this stage. That's why those information are out-of-date, and you must refresh the webpage once to get to see the latest values.
+
+
There is a workaround for this: refresh automatically the webpage (but delete the POST data to avoid an infinite loop). You just need to use this overloading code instead of the one above:
+
+
<source lang="php">
+
function customfields_field_aftersave_facture_global_coefficient (&$currentmodule, &$object, &$action, &$user, &$customfields, &$field, &$name, &$value, $fields) {
+
// Force refreshing total price
+
$object->update_price(0, 'auto');
+
// Force refresh the page to update prices that were printed before the custom field aftersave was triggered (and only if not creating the object because then there's no need to refresh)
+
if ($action !== 'add') print('<script type="text/javascript">window.location.href = window.location.pathname + window.location.search;</script>');
+
}
+
</source>
+
+
Another way to fix this issue would be to modify how CustomFields save the custom fields, by moving this stage at the very top. However, this would need another hook, which should be called at the very beginning of the page loading, which should be made only for this purpose (PageLoading), and should be available in all modules supported by CustomFields in order to not break anything.
+
+
Note that you will need to create one overloading function for each module you want to support with the global_coefficient custom field. For example, if you want to support both invoices and commercial proposals, you will need two overloading functions:
+
+
<source lang="php">
+
// Global coefficient for invoices (note the "facture" in the name of the function)
+
function customfields_field_aftersave_facture_global_coefficient (&$currentmodule, &$object, &$action, &$user, &$customfields, &$field, &$name, &$value, $fields) {
+
// Force refreshing total price
+
$object->update_price(0, 'auto');
+
// Force refresh the page to update prices that were printed before the custom field aftersave was triggered (and only if not creating the object because then there's no need to refresh)
+
if ($action !== 'add') print('<script type="text/javascript">window.location.href = window.location.pathname + window.location.search;</script>');
+
}
+
+
// Global coefficient for commercial proposals (note the "propal" in the name of the function)
+
function customfields_field_aftersave_propal_global_coefficient (&$currentmodule, &$object, &$action, &$user, &$customfields, &$field, &$name, &$value, $fields) {
+
// Force refreshing total price
+
$object->update_price(0, 'auto');
+
// Force refresh the page to update prices that were printed before the custom field aftersave was triggered (and only if not creating the object because then there's no need to refresh)
+
if ($action !== 'add') print('<script type="text/javascript">window.location.href = window.location.pathname + window.location.search;</script>');
+
}
+
</source>
+
+
= Modify the total price PER product/service line with a coefficient (without tampering the discount) =
Here we will go through the creation and management of a custom field called '''coefficient''' that will change the total price of each product by modifying it by the coefficient.
Here we will go through the creation and management of a custom field called '''coefficient''' that will change the total price of each product by modifying it by the coefficient.
Line 361:
Line 591:
== Change total price in database ==
== Change total price in database ==
−
Here we will use a "save" overloading function to change the total price directly in the database, thus we won't have to modify anything else (eg: in PDT or ODT) since the total price will be already updated in the database.
+
Here we will use a "save" overloading function to change the total price directly in the database, thus we won't have to modify anything else (eg: nor PDF templating nor ODT) since the total price will be already updated in the database.
Warning: this method will work only with CustomFields => 3.2.23 since the "save" overloading function did not work for products lines before.
Warning: this method will work only with CustomFields => 3.2.23 since the "save" overloading function did not work for products lines before.
Line 520:
Line 750:
</source>
</source>
−
=== Implementing the change of price in the Dolibarr interface ===
+
=== Implementing the change of total price in the Dolibarr interface ===
Unluckily there is not (yet) any hooking context to modify how lines of products/services are printed, thus the only thing you can do is directly edit the '''template file''' and manually put inside your code to load your custom field and print it the way you want using HTML formatting, for our example:
Unluckily there is not (yet) any hooking context to modify how lines of products/services are printed, thus the only thing you can do is directly edit the '''template file''' and manually put inside your code to load your custom field and print it the way you want using HTML formatting, for our example:
Line 540:
Line 770:
// Filling the $object with customfields (you can then access customfields by doing $object->customfields->cf_yourfield)
// Filling the $object with customfields (you can then access customfields by doing $object->customfields->cf_yourfield)
$linecf = new stdClass();
$linecf = new stdClass();
−
$linecf->id = $line->rowid;
+
$linecf->id = (!empty($line->id))?$line->id:$line->rowid;
−
$linecf->table_element = 'facturedet'; // you can use $this->table_element_line here instead of 'facturedet' if you want this feature to work for every module supported by CustomFields
+
$linecf->table_element = $object->table_element_line; // you can use $object->table_element_line here instead of 'facturedet' if you want this feature to work for every module supported by CustomFields
$customfields = customfields_fill_object($linecf);
$customfields = customfields_fill_object($linecf);
Line 547:
Line 777:
// Applying a multiplying/dividing coefficient to an HT price will give a mathematically correct TTC price since the taxes are also a multiplier
// Applying a multiplying/dividing coefficient to an HT price will give a mathematically correct TTC price since the taxes are also a multiplier
// However, if you want to apply other mathematical operations (like addition or substaction), you should use the total price with $line->total_ttc
// However, if you want to apply other mathematical operations (like addition or substaction), you should use the total price with $line->total_ttc
−
echo price($line->total_ht * $linecf->customfields->cf_coefficient);
+
if (!empty($linecf->customfields->cf_coefficient)) {
+
echo price($line->total_ht * $linecf->customfields->cf_coefficient);
+
} else {
+
echo price($line->total_ht);
+
}
?>
?>
</source>
</source>
Line 556:
Line 790:
Technical note: here we are using customfields_fill_object() instead of customfields_fill_object_lines() (the latter being specifically adapted to lines and thus should theoretically be used here) for performance reasons because the template file we are editing is called in a loop, and customfields_fill_object_lines() should be called outside a loop (because it already does the job that is done by the loop), so here we 'tricks' the customfields_fill_object() function to avoid this loop by submitting 'facturedet' as a module by itself (when in fact it's a product lines table, but it works the same way nevertheless). This is a good demonstration of the flexibility of the CustomFields functions and methods.
Technical note: here we are using customfields_fill_object() instead of customfields_fill_object_lines() (the latter being specifically adapted to lines and thus should theoretically be used here) for performance reasons because the template file we are editing is called in a loop, and customfields_fill_object_lines() should be called outside a loop (because it already does the job that is done by the loop), so here we 'tricks' the customfields_fill_object() function to avoid this loop by submitting 'facturedet' as a module by itself (when in fact it's a product lines table, but it works the same way nevertheless). This is a good demonstration of the flexibility of the CustomFields functions and methods.
+
+
=== Implementing the coefficient column in the Dolibarr interface ===
+
+
It's also possible to show the coefficient in a new column on the Dolibarr interface.
+
+
To do that, you need to do two things:
+
+
1- Add the column title "Coeff."
+
+
2- Add the generator that will input the coefficient value for each line.
+
+
==== '''Add the column title "Coeff."''' ====
+
+
Open in your favourite editor the file /htdocs/core/class/commonobject.class.php and inside the function printObjectLines (note the plural s), find the following lines of code:
+
+
<source lang="php">
+
// Total HT
+
print '<td align="right" width="50">'.$langs->trans('TotalHTShort').'</td>';
+
</source>
+
+
This is what prints the Total HT price column. We will place the Coeff column just before.
+
+
So, just above this code, add the following:
+
+
<source lang="php">
+
// Coefficient (CustomFields)
+
dol_include_once('/customfields/class/customfields.class.php');
+
$customfields = new CustomFields($this->db, $object->table_element_line);
+
$coeff_field = $customfields->fetchFieldStruct('coefficient');
+
if (!empty($coeff_field)) {
+
print '<td align="right" width="50">'.$langs->trans('Coeff.').'</td>';
+
}
+
</source>
+
+
This will take care of showing the Coeff. column, but only for modules where you created such a custom field (because the file we modified is a common object for all modules in Dolibarr, not just invoices, thus this modification will gracefully skip this custom field if it does not exists for other modules).
+
+
==== '''Add the generator''' ====
+
+
Open the file /htdocs/core/tpl/objectline_view.tpl.php and try to find the following block of code:
+
+
<source lang="php">
+
<?php if ($line->special_code == 3) { ?>
+
<td align="right" class="nowrap"><?php $coldisplay++; ?><?php echo $langs->trans('Option'); ?></td>
+
<?php } else { ?>
+
<td align="right" class="nowrap"><?php $coldisplay++; ?><?php echo price($line->total_ht); ?></td>
+
<?php } ?>
+
</source>
+
+
This is what prints the total HT price value for each line.
+
+
Just above of this block of code, add the following:
+
+
<source lang="php">
+
<?php
+
// Coefficient (CustomFields)
+
// Include the facade API of CustomFields
+
dol_include_once('/customfields/lib/customfields_aux.lib.php');
+
+
// Filling the $object with customfields (you can then access customfields by doing $object->customfields->cf_yourfield)
+
$linecf = new stdClass();
+
$linecf->id = (!empty($line->id))?$line->id:$line->rowid;
+
$linecf->table_element = $object->table_element_line; // you can use $this->table_element_line here instead of 'facturedet' if you want this feature to work for every module supported by CustomFields
+
$customfields = customfields_fill_object($linecf);
+
if (isset($linecf->customfields->cf_coefficient)) {
+
?>
+
<td align="right" class="nowrap"><?php $coldisplay++; ?><?php echo $linecf->customfields->cf_coefficient; ?></td>
+
<?php } ?>
+
</source>
+
+
Just like for the column title, this code will take care of generating the coefficient value only if the custom field is defined, because this file is also a generic template for all modules of Dolibarr.
+
+
At this point, everything is done, you should see the following:
+
[[File:Cf_wiki_coeff_column.png]]
+
+
=== Implementing the change of price in margin module ===
+
+
If you enabled the margin module, you should see that the coefficient is not applied there, but it's easy to fix that.
+
+
Open the file /htdocs/core/class/commonobject.class.php and find the function getMarginInfos(), then inside find the following lines:
+
+
<source lang="php">
+
foreach($this->lines as $line) {
+
if (empty($line->pa_ht) && isset($line->fk_fournprice) && !$force_price) {
+
$product = new ProductFournisseur($this->db);
+
if ($product->fetch_product_fournisseur_price($line->fk_fournprice))
+
$line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
+
if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == "2" && $product->fourn_unitcharges > 0)
+
$line->pa_ht += $product->fourn_unitcharges;
+
}
+
// si prix d'achat non renseigné et devrait l'être, alors prix achat = prix vente
+
if ((!isset($line->pa_ht) || $line->pa_ht == 0) && $line->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) {
+
$line->pa_ht = $line->subprice * (1 - ($line->remise_percent / 100));
+
}
+
</source>
+
+
This is where the lines are filled with margin infos. The price has just been fetched here, and we will now modify it with the coefficient before the price gets used for margin computation.
+
+
Just below the code we found, paste the following:
+
+
<source lang="php">
+
// Coefficient (CustomFields)
+
// Include the facade API of CustomFields
+
dol_include_once('/customfields/lib/customfields_aux.lib.php');
+
// Filling the $object with customfields (you can then access customfields by doing $object->customfields->cf_yourfield)
+
$linecf = new stdClass();
+
$linecf->id = (!empty($line->id))?$line->id:$line->rowid;
+
$linecf->table_element = $line->table_element;
+
$customfields = customfields_fill_object($linecf);
+
if (!empty($linecf->customfields->cf_coefficient)) {
+
$line->pa_ht = $line->pa_ht * $linecf->customfields->cf_coefficient;
+
$line->subprice = $line->subprice * $linecf->customfields->cf_coefficient;
+
}
+
</source>
+
+
That's all, the price should be reflected in the margin.
+
[[File:Cf_wiki_coeff_margin.png]]
+
+
=== Implementing the change of price in remaining debt to pay ===
+
+
Open /htdocs/core/class/commonobject.class.php and look for the function update_price().
+
+
You should see the following:
+
+
<source lang="php">
+
function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller='')
+
{
+
global $conf;
+
+
include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
+
</source>
+
+
Just below the include_once line, add the following:
+
+
<source lang="php">
+
// Coefficient (CustomFields)
+
include_once DOL_DOCUMENT_ROOT.'/customfields/class/customfields.class.php';
+
include_once DOL_DOCUMENT_ROOT.'/customfields/conf/conf_customfields_func.lib.php';
+
$customfields = new CustomFields($this->db, $this->table_element_line);
+
// Fetching line ids from parent object id
+
$line_ids = $customfields->fetchAny('rowid', MAIN_DB_PREFIX.$this->table_element_line, $this->fk_element.' = '.$this->id);
+
$line_ids = array_values_recursive('rowid', $line_ids);
+
// Load custom fields
+
$cf_records = $customfields->fetch($line_ids);
+
// Reassociate the records with the line id (instead of the customfields record id)
+
$cf_line_cfrowid_to_rowid = array_reassociate('rowid', 'fk_'.$this->table_element_line, $cf_records);
+
$tmp = $cf_records;
+
$cf_records = array();
+
foreach ($tmp as $k=>$v) { $cf_records[$cf_line_cfrowid_to_rowid[$k]] = $tmp[$k]; }
+
</source>
+
+
This will load the coefficient custom field (and also any other custom field you have defined for lines).
+
+
Now scroll below, and you should see this:
+
+
<source lang="php">
+
while ($i < $num)
+
{
+
$obj = $this->db->fetch_object($resql);
+
+
// Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
+
+
if ($forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
+
{
+
$localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
+
$tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array);
+
$diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
+
if ($diff)
+
{
+
$sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
+
dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
+
$resqlfix=$this->db->query($sqlfix);
+
if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
+
$obj->total_tva = $tmpcal[1];
+
$obj->total_ttc = $tmpcal[2];
+
//
+
}
+
}
+
</source>
+
+
Just after, add the following:
+
+
<source lang="php">
+
// Coefficient (CustomFields)
+
$cf_coeff = $cf_records[$obj->rowid]->coefficient;
+
if (empty($cf_coeff) and $cf_coeff !== 0) $cf_coeff = 1; // by default, an empty coefficient = 1
+
$obj->total_ht = $obj->total_ht * $cf_coeff;
+
$obj->total_tva = $obj->total_tva * $cf_coeff;
+
$obj->total_localtax1 = $obj->total_localtax1 * $cf_coeff;
+
$obj->total_localtax2 = $obj->total_localtax2 * $cf_coeff;
+
$obj->total_ttc = $obj->total_ttc * $cf_coeff;
+
</source>
+
+
This should do the trick. Now go to one of your invoices (or whatever module you are targetting), and try to add/edit a product/service line to force refresh the total price. You should then see this:
+
[[File:Cf_wiki_coeff_remaining_debt.png]]
= Custom tax per product =
= Custom tax per product =
Line 608:
Line 1,036:
for ($i = 0 ; $i < $nblignes ; $i++)
for ($i = 0 ; $i < $nblignes ; $i++)
−
$object->total_custom_tax = $total_custom_tax + $object->productslines->$line_product_id->cf_custom_tax;
+
$object->total_custom_tax += $object->productslines->$line_product_id->cf_custom_tax;
</source>
</source>
Line 620:
Line 1,048:
<source lang="php">
<source lang="php">
−
$object->total_ttc = $object->total_ttc + $object->total_custom_tax;
+
$object->total_ttc = $object->total_ttc + $object->total_custom_tax; // prepend this to add the custom tax to the total
$pdf->MultiCell($largcol2, $tab2_hl, price($sign * $object->total_ttc, 0, $outputlangs), $useborder, 'R', 1);
$pdf->MultiCell($largcol2, $tab2_hl, price($sign * $object->total_ttc, 0, $outputlangs), $useborder, 'R', 1);
</source>
</source>